Ajax的请求步骤

ajax是一种异步请求数据的技术,对改善用户的体验和程序的性能有很大的帮助;

下面来看看请求过程

1.创建一个XMLHttpRequest()对象,创建一个异步调用对象;

var xhr;
if(window.XMLHttpRequest){
  xhr=new XMLHttpRequest();
}else{
  xhr=new ActiveXObject('Microsoft.XMLHTTP');
}
 

  

2.向服务器发送请求

xhr.open(method,url,async);
xhr.send()

 

3.open的三个参数分别为

method:请求方式(post/get);

url:请求的路径;

async:true表示异步,false表示同步

如果是true,会执行send()方法再继续执行,不等待来自服务器的响应;

会有一个onreadystatechange方法来根据服务器返回的状态来进行进行操作;

 

注:post与get请求方式又不相同

当使用post时,send里面带参数,get就不用;

post请求要设置请求头参数;

xhr.open('post',"xxx",true);
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
xhr.send("firstName=haha&lastName=xixi")

 

现在来看看同步跟异步的差异

//同步
xhr.open('get','xxx',false);
xhr.send();
document.ID.innerHTML=xhr.responseText;

//异步
xhr.onreadystatechange=function(){
   if(xhr.readyState==4&&xhr.status==200){
    document.ID.innerHTML=xhr.responseText;
 }

}

其中状态一共有五个:

0:请求未初始化

1:服务器连接已经建立

2:请求已经接受

3:请求已经处理

4:请求已经完成,响应已就绪

 

状态码分别为,有以下几种常见:

200:"OK"

304:该资源在上次请求后没有任何修改

403:禁止;服务器拒绝访问

404:未找到,服务器找不到请求的地址

500:服务器内部错误,无法完成请求

 

下面我们来看看完整的封装代码

function XHR(){
  if(window.XMLHttpRequest){
     return new XMLHttRequest()
  }
    return new ActiveXObject('Microsoft.XMLHTTP');
}

function getParam(url){
   "use strict";
    let str="";
    for(var k in url){
      str+=k+"="+url[k]+"&";
   }
}

function ajax(opts){
  opts.type=opts.type==undefined?"get":opts.type;
  opts.async=opts.async==undefined?true:opts.async;
  opts.dataType=opts.dataType==undefined?"json":opts.dataType;

let xhr=XHR(); 
if(opts.type=="get"){
   xhr.open("get",opts.url+'?'+getParam(opts.data),opts.async);
   xhr.send(null)
}else{
   xhr.open("post",opts.url,opts.async);
   xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
   xhr.send(getParam(opts.data))
}
 
if(opts.async){
   xhr.onreadystatechange=function(){
      if(xhr.readyState==4){
        result()
     }
   }
 }else{
    result()
  }

}
//ssuccess为请求成功的回调函数
function result(){
  if(xhr.status==200){
     if(opts.dataType=="json"){
       opts.success(JSON.parse(xhr.responseText))
    }else{
       opts.success(xhr.responseText)
     }
  }


}

 

转载于:https://www.cnblogs.com/xxcnhj/p/11165927.html

你可能感兴趣的:(Ajax的请求步骤)