Ajax,2005年诞生的,它是一种在客户端创建一个异步请求的技术,本质上它不算创新,是一组技术的组合。它的核心对象是XMLHttpRequest。
Ajax GET数据
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
// To do with xhr.response
};
xhr.onerror = function() {
// Handling errors
};
xhr.send();
Ajax POST数据
将data数据作为httpRequest.send(data)参数中调用。
function makeRequest(url, userName) {
...
httpRequest.onreadystatechange = alertContents;
httpRequest.open('POST', url);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send('userName=' + encodeURIComponent(userName));
}
Fetch API提供了一个全局fetch()方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。这种功能以前是使用XMLHttpRequest实现的。与XMLHttpRequest不同的是,它的API不是事件机制,而采用了目前流行的Promise方式处理。
fetch('doAct.action').then(function(res) {
if (res.ok) {
res.text().then(function(obj) {
// Get the plain text
})
}
}, function(ex) {
console.log(ex)
})
Fetch结合async/await使用
await语法后面的表达式是一个Promise对象或者任何要等待的值。而正好全局fetch()方法执行后会返回一个包含响应结果的promise。
Fetch GET
function delStorage(id: number){
return fetch(`${ajaxUrl}acg-material/del-design-draw?id=${id}`,{credentials: 'include'}).then(response=>{
if(response.ok){
return response.json();
}
return new Error(response.statusText);
}).catch(error => console.error(error));
}
Fetch POST
function AddChannel(data: any){
return fetch(`${ajaxUrl}acg-material/add-video-channel`, {
credentials: 'include',
method: 'POST', // or 'PUT'
body: toFormData(data)// data can be `string` or {object}!
}).then(response=>{
if(response.ok){
return response.json();
}
return new Error(response.statusText);
}).catch(error => console.error(error));
}
上面的toFormData方法是包装一个JS对象转formData对象:
function toFormData(data: any){
const formData = new FormData();
Object.keys(data).map(key=>{
formData.append(key,data[key]);
});
return formData;
}
Fetch方法默认是不携带cookie
Fetch请求数据时,有时需要用到cookie记录登陆状态,否则后台会返回未登陆状态。Fetch方法默认是不携带cookie,需要在代码里加入一行代码credentials: 'include'。
fetch(url, {
method: 'POST',
headers: {
...
},
credentials: 'include'
}).then(
resp => resp.json()
).then(
...
).catch(
...
);
或者headers里设置cookie属性也是可以的
fetch(url, {
method: 'POST',
headers: {
...
'cookie': xxxxx
},
}).then(
resp => resp.json()
).then(
...
).catch(
...
);
参考:
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
https://www.cnblogs.com/snandy/p/5076512.html