解释ajax的工作原理

1、创建ajax对象(XMLHttpRequest/ActiveXObject(Microsoft.XMLHttp))

2、打开链接 open(请求方式,'请求路径',同步/异步)

3、发送 send()

4、当ajax对象完成第四步(onreadystatechange)数据接收完成,判断对象状态码(readystate) 4  HTTP响应完全接收  在判断http响应状态(status)200-300之间或者304(缓存)执行回调函数 获取的数据转成字符串格式(responseText)

 1 function ajax(json){
 2    //1.创建一个ajax对象;
 3    if(window.XMLHttpRequest){
 4       var oAjax = new XMLHttpRequest();
 5    }else{
 6       var oAjax = new ActiveXObject('Microsoft.XMLHTTP');
 7    }
 8 
 9    //考虑默认值:
10    if(!json.url){
11       alert('请输入合理的请求地址!');
12       return;
13    }
14    json.type = json.type || 'get';
15    json.time = json.time || 5000;
16    json.data = json.data || {};
17 
18    //判断用户传递的是get还是post请求:
19    switch (json.type.toLowerCase()){
20       case 'get':
21          //2.打开请求;
22          oAjax.open('get',json.url+'?'+json2url(json.data),true);
23          //3.发送数据:
24          oAjax.send();
25          break;
26       case 'post':
27          //打开请求;
28          oAjax.open('post',json.url,true);
29          //设置请求头;
30          oAjax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
31          //发送数据;
32          oAjax.send(json2url(json.data));
33    }
34    //4.获取响应数据
35    oAjax.onreadystatechange = function() {
36       if (oAjax.readyState == 4) {
37          if (oAjax.status >= 200 && oAjax.status < 300 || oAjax.status == 304) {
38             //如果外边传递了成功的回调函数,那么就执行,
39             json.success && json.success(oAjax.responseText);
40          } else {
41             //如果外边传递了失败的回调函数,那么就执行,
42             json.error && json.error(oAjax.status);
43          }
44          clearTimeout(timer);//规定时间内取到数据后清除定时器;
45       }
46    };
47    var timer;
48    timer = setTimeout(function(){//设置网络响应超时;
49       alert('网络响应超时,请稍后再试');
50       oAjax.onreadystatechange = null;//网络超时后清除事件;
51    },json.time);
52 }

 

posted @ 2017-06-08 22:25  hi?*  阅读(859)  评论(0编辑  收藏  举报