jQuery让AJAX变得更加的简单,但是一直使用的早期的XMLHttpRequest (XHR)提供的ajax方式进行异步操作。
Fetch API 使用了 Promises,它让接口更简单、简洁,避免了回调的复杂性,省去了使用复杂的 XMLHttpRequest API。
如果需要抛弃那些古董浏览器,就赶紧换上Fetch()方法把,不用为了单独一个异步功能引用整个jQuery库了。
下面提供一个简单的例子:
fetch("http://blog.7cuu.com/").then(function(data){
console.log(data);
});看看浏览器console调试页面是不是出现了想要的数据,虽然是新特新,但是也是有跨域限制的改成自己需要访问的地址就好了。
如果要获取json数据呢,就看下面的代码:
fetch("http://blog.7cuu.com/").then(function(data){
data.json().then(function(json){
console.log(data);
});
});来一个get和post的获取方法吧
function getJson(url, callback) {
fetch(url, {}).then((res) => {
res.json().then((res) => {
if(callback != null){
callback(res);
}
});
})
}
function postJson(url, body, callback) {
fetch(url, {
method: "POST",
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
}).then((res) => {
res.json().then((res) => {
if(callback != null){
callback(res);
}
})
})
}使用同步方法请求
/**
* 网络请求,支持同步返回
* @param data [url,method,header,data,@success,@fail]
*/
async function requset(data) {
//格式化body字段
let body = data.data ? data.data : [];
body = Object.keys(body).map(key => {
return key + "=" + body[key];
}).join('&');
//异步
return new Promise((resolve, reject) => {
fetch(data.url, {
method: data.method ? data.method : "GET",
//mode: 'cors',
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
body: body,
}).then(res => {
res.json().then(res => {
//成功抛出
if (data.success != null) {
data.success(res);
}
return resolve(res);
})
}).catch(res => {
//异常抛出
if (data.fail != null) {
data.fail(res);
}
return reject(res);
});
});
}至于post或者更多高级方法下次再写吧。

