1.原生XHR
var xhr = new XMLHttpRequest()
//xhr.responseType = 'json'可以將返回json字符串結(jié)果自動(dòng)轉(zhuǎn)換成對(duì)象
xhr.open(method, uri, true)
xhr.send('body')//請(qǐng)求主體(上傳的參數(shù))
xhr.onreadystatechange = function(){
if(xhr.readyState===4){
if(xhr.status>=200 && xhr.status<300){ //響應(yīng)完成且成功
console.log(xhr.responseText);
}else{ //響應(yīng)完成但不成功
alert('響應(yīng)完成但失?。?+xhr.status);
}
}
}
2.JQuery--AJAX
//需引入JQuery <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
$.ajax({
url: '/add/', // 請(qǐng)求地址
method: 'post', // 請(qǐng)求方式
data:{'a':$("#first").val() ,'b':$("#second").val() }, // 獲取input標(biāo)簽數(shù)據(jù)
success:function (data) {
//成功觸發(fā)
},
error:function (error) {
//失敗,觸發(fā)
}
})
好處:可以將對(duì)象數(shù)據(jù)自動(dòng)序列化成對(duì)應(yīng)的請(qǐng)求頭對(duì)應(yīng)形式的數(shù)據(jù)
3.原生fetch
-
Fetch API是新的ajax解決方案Fetch會(huì)返回Promise -
fetch不是ajax的進(jìn)一步封裝,而是原生js,沒(méi)有使用XMLHttpRequest對(duì)象。
語(yǔ)法:fetch(url, options).then()
fetch(url, {
//body: JSON.stringify(data), // body(上傳的數(shù)據(jù))需要對(duì)應(yīng)header中的'Content-Type',序列化成不同的字符串形式
body:'key=value&key=value',
headers: {
//'content-type': 'application/json'
'content-type':'application/x-www-form-urlencoded'
},
method: 'POST', // *GET默認(rèn)get請(qǐng)求, POST, PUT, DELETE, etc.
})
4.axios
-
Axios是一個(gè)基于promise的HTTP庫(kù),可以用在瀏覽器和node.js中 - 特點(diǎn):
- 從瀏覽器中創(chuàng)建
XMLHttpRequests - 從
node.js創(chuàng)建http請(qǐng)求 - 支持
Promise API - 攔截請(qǐng)求和響應(yīng)
- 從瀏覽器中創(chuàng)建
-
語(yǔ)法
①. 安裝:npm install axios -S
或者靜態(tài)引入:<script src="https://unpkg.com/axios/dist/axios.min.js"></script>②. 使用請(qǐng)求方式
get方式
// 為給定 ID 的 user 創(chuàng)建請(qǐng)求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 可選地,上面的請(qǐng)求可以這樣做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
post方式
axios.post('/login',qs.stringify({
user:'xxx',
pwd:'密碼'
}))
.then(res=>{
console.log(res);
console.log(res.data);
})
③. 執(zhí)行多個(gè)并發(fā)請(qǐng)求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 兩個(gè)請(qǐng)求現(xiàn)在都執(zhí)行完成
}));