1. 程式人生 > 其它 >js封裝ajax

js封裝ajax

 
1 //呼叫方式:
2 ajax(    
3   'http://www.baidu.com',
4   {name:'json'}    
5   ).then((res)=>{
6     console.log(res);
7   })

 

function ajax(url,data) {
    return new Promise((resolve,reject)=>{
        let xhr = new XMLHttpRequest();
        let temp = '?';
        for(let key in data){
            temp 
= temp + key + '=' + data[key] + '&'; } temp = temp.substr(0, temp.length - 1); xhr.open('get', url+temp); xhr.setRequestHeader("Content-type", 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function () {      if (xhr.readyState == 4 && xhr.status == 200) { resolve(xhr.responseText); } } xhr.send(temp); }); }

 

  其中:

 1 //(如果需要設定特殊的表單提交方式)則修改
 2 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 3 //application/x-www-form-urlencoded -> 
 4 let data = "name=json";
 5 
 6 //application/json -> 
 7 let data = JSON.stringify({name:'json'});
 8 
 9 //multipart/form-data -> 
10 let data = new
FormData(); 11 data.append('name','json');