1. 程式人生 > >Ajax異步請求幾步曲——可直接引入

Ajax異步請求幾步曲——可直接引入

javascrip 消息 script change 出錯 發送 scrip 不同的 new

引入函數ajax(method,url,postStr,dataType="json"){

  return new Promise((resolve,reject)=>{...}

)};

function ajax(method,url,postStr,dataType="json"){
  return new Promise((resolve,reject)=>{

method: 請求方式,string類型,常取值:get post...

url:請求地址,string類型

postStr:當method取post時需要發送給服務端的數據字符串

dataType:響應消息頭,默認json,告訴瀏覽器是什麽格式以及什麽類型

1.獲取xhr

var xhr = function(){
  if(window.XMLHttpRequest){
    return new XMLHttpRequest();
  }else{
    return new ActiveXObject("Microsoft.XMLHttp")
  }
}

2.創建請求

xhr.open(method,url,true);

3.設置請求消息頭

如果method取值為post,則需修改消息頭

if(method=="post"){
      xhr.setRequestHeader(
        "Content-Type", "application/x-www-form-urlencoded");
    }

  

4.設置回調並發送

xhr.onreadystatechange = function(){
  if(xhr.readyState==4){
    if(xhr.status==200){
      if(url.indexof(".php")!=-1&&dataType.toLowerCase()=="json"){
        console.log(xhr.responseText);
        resolve(JSON.parse(xhr.responseText)); 
      }else{
        console.log(xhr.responseText);
        resolve(xhr.responseText);
      }
    }else{
        reject("ajax出錯了"+xhr.status);
    }
  }
  xhr.send(postStr);
}

  完整代碼如下,服務器PHP,用JSON解析,不同的可以相應改動一下。

 1 function ajax(method,url,postStr,dataType="json"){  //
 2   return new Promise((resolve,reject)=>{
 3     //1、獲取 xhr
 4     var xhr = (function(){
 5       if(window.XMLHttpRequest){
 6         return new XMLHttpRequest();
 7       }else{
 8         return new ActiveXObject("Microsoft.XMLHttp");
 9       }
10     })();
11     //2、創建請求
12     xhr.open(method,url,true);
13     
14     //4、設置請求消息頭
15     if(method=="post"){
16       xhr.setRequestHeader(
17         "Content-Type", "application/x-www-form-urlencoded");
18     }
19     //3、設置回調
20     xhr.onreadystatechange=function(){
21       if(xhr.readyState == 4)
22         if(xhr.status == 200){
23           if(url.indexOf(".php")!=-1
24             &&dataType.toLowerCase()=="json"){
25             console.log(xhr.responseText);
26             resolve(JSON.parse(xhr.responseText));
27           }else{
28             console.log(xhr.responseText);
29             resolve(xhr.responseText);
30           }
31         }else
32           reject("ajax出錯啦!"+xhr.status);
33     }
34     //5、發送
35     xhr.send(postStr);
36   })
37 }

Ajax異步請求幾步曲——可直接引入