一、发送请求

Ajax中通过XMLHttpRequest对象发送异步方式的后台请求时。通常有两种方式的请求,一种是GET请求,另一种是POST请求。发送请求一般要经过4个步骤分别是:

(1)初始化XMLHttpRequest对象

(2)为XMLHt指定一个返回结果的回调函数,用于返回结果的处理

(3)创建一个与服务器的连接。指定发送的请求是GET还是POST且是否采用异步方式发送请求

(4)向服务器发送请求。

 

 1 <script type="text/javascript">
 2     
 3     function checkBrowerType(){
 4         //第一步:初始化XMLHttpRequest对象
 5         var http_request = false;
 6         if(window.XMLHttpRequest){                  //非IE浏览器; 在调用window.ActiveXObject将返回一个对象,或是null(如果返回一个对象则为true,返回null则为false)
 7             http_request = new XMLHttpRequest();    //创建XMLHttpRequest对象
 8             
 9         }else if(window.ActiveXObject){
10             try{
11                 http_request = new ActiveXObject("Msxml2.XMLHTTP");    //创建XMLHttpRequest对象
12             }catch(e){
13                 try{
14                     http_request = new ActiveXObject("Microsoft.XMLHTTP");    //创建XMLHttpRequest对象
15                 }catch(e){
16                     
17                 }
18             }            
19         }
20         if(!http_request){
21             alert("不能创建XMLHttpRequest对象实例");
22             return false;
23         }
24         //第二步:设置回调函数
25         http_request.onreadystatechange = getResult;    //调用返回处理函数
26         /*
27             注意:如果XMLHttpRequest对象的onreadystatechange属性指定回调函数时,
28             不能指定要传递的参数。如果要指定参数可以使用以下方法:
29             http_request.onreadystatechange = function(){
30             getResult(param)
31         };
32         */
33         
34         //第三步:创建一个与服务器的连接,(请求采用GET或POST请求方式,以及是否采用异步方式)
35         http_request.open("GET",url,true);
36         //第四步:向服务器发送请求
37         http_request.send(null);
38     }
39     /*编写回调函数getResult()*/
40     function getResult(){
41         
42     }
43 </script>
查看代码

相关文章:

  • 2021-11-23
  • 2021-03-31
  • 2021-12-29
  • 2022-12-23
  • 2022-12-23
  • 2021-12-24
  • 2022-02-28
  • 2021-10-15
猜你喜欢
  • 2021-06-05
  • 2021-12-22
  • 2021-08-07
  • 2022-12-23
  • 2021-08-29
  • 2022-12-23
  • 2022-02-16
相关资源
相似解决方案