js封裝ajax
阿新 • • 發佈:2022-04-10
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 = newFormData(); 11 data.append('name','json');