码迷,mamicode.com
首页 > Web开发 > 详细

js方式的异步请求

时间:2015-09-03 23:23:22      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

 1 有的企业要求你要会写,
 2     *1. 异步请求的get方式
 3         代码:
 4             //创建一个XmlHttpRequest请求
 5             function createXmlHttpRequest(){
 6                 //声明一个请求,并是设置为空
 7                 var xhr=null;
 8                 try{
 9                     //兼容IE浏览器的请求
10                     xhr=new ActiveXObject("microsoft.xmlhttp");
11                 }catch(e){
12                     try{
13                         //其他浏览器的请求对象
14                         xhr=new XmlHttpRequest();
15                     }catch(e){
16                         alert("你的浏览器太差!");
17                     }
18                 }
19                 //返回请求
20                 return xhr;
21             }
22             
23             //创建异步get请求,在窗口的加载的时候执行函数
24             window.onload=function(){
25                 
26                 //界面元素的单击事件之后完成异步请求
27                 document.getElementById("").onclick=function(){
28                     //获取请求对象,局部依赖该对象
29                     var xhr=createXmlHttpRequest();
30                     //请求对象的get请求
31                     xhr.open("get",url);
32                     //请求对象发送数据为空
33                     xhr.send(null);
34                     //请求对象的请求完之后的分发的数据
35                     //请求对象的准备状态的改变事件之后执行函数
36                     xhr.onreadystatechange=function(){
37                         //请求对象的准备状态为4时,请求成功
38                         if(xhr.readyState==4){
39                             //请求状态为200或者304时请求成功
40                             if(xhr.status==200 || xhr.status==304){
41                                 //获取服务器相应过来的数据
42                                 var data=xhr.responseText;
43                                 
44                                 alert(data);
45                             }
46                         }
47                     }
48 
49                 }
50             }
51     *2. 异步请求的post方式
52         //1. 创建请求对象,同上,略
53 
54         //2. 窗口加载的时候,创建异步请求
55         window.onload=function(){
56             //请求完成之后服务器响应的数据
59             xhr.onreadystatechange=function(){
           //创建请求对象
           var xhr=createXmlHttpRequest();
 
60 //请求对象的准备状态为4时,响应成功 61 if(xhr.readyState==4){ 62 //请求状态为200或者304时请求成功 63 if(xhr.status==200 || xhr.status==304){ 64 //获取服务器相应过来的数据 65 var data=xhr.responseText; 66 67 alert(data); 68 } 69 } 70 } 71 //请求对象向服务器请求数据 72 xhr.open("post",url); 73 //设置请求体的数据编码方式 74 xhr.setRequestHeader("content-type","application/x-www-urlencoded"); 75 //请求对象向服务器发送数据,parameter就是要提交的参数 76 xhr.send(parameter); 77 78 }

 

js方式的异步请求

标签:

原文地址:http://www.cnblogs.com/liaowanzhong/p/4780917.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!