今天,看書悯恍,發(fā)現(xiàn)有涉及到此三種前后端連接的方法库糠,我因此對此進(jìn)行了學(xué)習(xí),新手小菜鳥涮毫,有錯(cuò)誤請見諒瞬欧。
1.jQuery ajax
這里運(yùn)用了jQuuery已經(jīng)封裝好的ajax,使用之前需要引包,但缺點(diǎn)是JQuery整個(gè)項(xiàng)目太大罢防,單純使用ajax卻要引入整個(gè)JQuery非常的不合理艘虎,且多個(gè)請求之間如果有先后關(guān)系的話,就會(huì)出現(xiàn)回調(diào)地獄篙梢。
$.ajax({
type: 'POST',
url: 'url',
data: data,
dataType: dataType,
success: function () {},
error: function () {}
});
回調(diào)地獄可以使用Promise解決顷帖。
function load() {
return new Promise((resovel, reject) => {
$.ajax({
type: 'POST',
url: 'url',
data: data,
dataType: dataType,
success: function(res) {
resolve(res);
},
error: function(err) {
reject(err);
}
});
});
}
load().then(data => {
console.log(data); // 請求到的數(shù)據(jù)
console.log('請求數(shù)據(jù)成功');
}, err => {
console.log('請求失敗',err);
});
2.axios
axios是Promise的實(shí)現(xiàn)版本,符合最新的ES規(guī)范,使用前也需要引包渤滞,使用如下
axios({
method: 'post',
url: 'url',
data: data
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
3.fetch
fetch號稱是AJAX的替代品贬墩,是在ES6出現(xiàn)的,使用了ES6中的promise對象妄呕。Fetch是基于promise設(shè)計(jì)的陶舞。Fetch的代碼結(jié)構(gòu)比起ajax簡單多了,參數(shù)有點(diǎn)像jQuery ajax绪励。但是肿孵,fetch不是ajax的進(jìn)一步封裝,而是原生js疏魏。
Fetch獲取數(shù)據(jù)
還有其他方法來處理不同類型的響應(yīng)停做。如果請求一個(gè)XML格式文件,則調(diào)用response.text大莫。如果請求圖片蛉腌,使用response.blob方法。所有這些方法(response.json等等)返回另一個(gè)Promise只厘,所以可以調(diào)用.then方法處理我們轉(zhuǎn)換后的數(shù)據(jù)烙丛。
fetch('url')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
Fetch發(fā)送數(shù)據(jù)
fetch('url', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(...)
})
.then(data => console.log(data))
.catch(error => console.log(error));
如有問題,可以聯(lián)系本人羔味,請見諒河咽。