zoukankan      html  css  js  c++  java
  • Ajax——使用XMLHttpResquest实现Ajax

    发送请求

    利用XMLHttpRequest实例与服务器进行通信包含以下3个关键部分:

    ——onreadystatechange事件处理函数

    ——open方法

    ——send方法

    onreadystatechange:

    ——该事件处理函数由服务器触发,而不是用户

    ——在Ajax执行过程中,服务器会通知客户端当前的通信状态。这依靠更新XMLHttpRequest对象的readyState来实现。

    改变readyState属性是服务器对客户端连接操作的一种方式。每次resdyState属性凡人改变都会触发readystatechange事件

    在某些情况下,有些浏览器会把多个XMLHttpResquest请求的结果缓存在同一个URL。如果对每个请求响应不同,就会带来不好的结果。

    在此将时间戳追加到URL的最后,就能确保URL的唯一性,从而避免浏览器缓存结果

    index.jsp

     1 <title>Insert title here</title>
     2 <script type="text/javascript">
     3     
     4     window.onload = function(){
     5         //1.获取a节点,并为其添加onclick响应函数
     6         document.getElementsByTagName("a")[0].onclick = function(){
     7             
     8             //3.创建一个XMLHttpResquest对象
     9             var request = new XMLHttpRequest();
    10             
    11             //4.准备发送请求的数据:url
    12             var url = this.href + "?time" + new Date();
    13             var method = "GET";//POST
    14             
    15             //5.调用XMLHttpResquest对象的open方法
    16             request.open(method,url);
    17             //request.setRequestHeader("ContentType","application/x-www-form-urlencoded");
    18             
    19             //6.调用XMLHttpResquest对象的send方法
    20             request.send(null));
    21             //request.send("name='atguigu'");
    22             
    23             //7.为XMLHttpRequest对象添加onreadystatechange响应函数
    24             request.onreadystatechange = function(){
    25                 //8.判断响应是否完成:XMLHttpRequest对象的readyState属性值为4的时候
    26                 if(request.readyState == 4){
    27                     //9.再判断响应是否可用:XMLHttpRequest对象status属性值为200
    28                     if(request.status == 200 || request.status == 304){
    29                         //10.打印响应结果:responseText
    30                         alert(request.responseText);
    31                     }
    32                 }
    33                 
    34             }
    35             //2.取消a节点的默认行为
    36             return false
    37         }
    38         
    39     }
    40     
    41 </script>
    42 
    43 </head>
    44 <body>
    45 
    46 <a href="helloAjax.txt">HelloAjax</a>
    47 
    48 </body>
  • 相关阅读:
    131. Palindrome Partitioning
    130. Surrounded Regions
    129. Sum Root to Leaf Numbers
    128. Longest Consecutive Sequence
    125. Valid Palindrome
    124. Binary Tree Maximum Path Sum
    122. Best Time to Buy and Sell Stock II
    121. Best Time to Buy and Sell Stock
    120. Triangle
    119. Pascal's Triangle II
  • 原文地址:https://www.cnblogs.com/Codinginging/p/10779143.html
Copyright © 2011-2022 走看看