提取与AjaxCall [英] Fetch vs. AjaxCall
本文介绍了提取与AjaxCall的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
典型的AJAX和Fetch API有什么区别?
What is the difference between typical AJAX and Fetch API?
考虑这种情况:
function ajaxCall(url) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
if (req.status == 200) {
resolve(req.response);
} else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send();
});
}
ajaxCall('www.testSite').then(x => {
console.log(x)
}) // returns html of site
fetch('www.testSite').then(x => {
console.log(x)
}) // returns object with information about call
这是fetch
调用返回的内容:
Response {type: "cors", url: "www.testSite", status: 200, ok: true, statusText: "OK"…}
为什么它返回不同的东西?
Why does it return different things?
fetch
是否可以返回与典型AJAX调用相同的内容?
Is there a way for fetch
to return the same thing as a typical AJAX call?
推荐答案
Fetch API内置了适用于不同数据类型的方法.
对于普通的text/html,您可以使用text()
方法,该方法也会返回一个promise,并将其与另一个调用链接.
The Fetch API has built in methods for different datatypes.
For just regular text/html you'd use the text()
method, which returns a promise as well, and chain it with another then call.
fetch('www.testSite').then( x => {
return x.text();
}).then( y => {
console.log(y);
});
返回的内容的内置内容如下
The built-ins for the returned content is as follows
-
clone()
-创建Response对象的克隆. -
error()
-返回一个 与网络错误相关联的新Response对象. -
redirect()
-使用其他URL创建新的响应. -
arrayBuffer()
-返回使用ArrayBuffer解析的promise. -
blob()
-返回以Blob解析的promise. -
formData()
-返回使用FormData对象解析的Promise. -
json()
-返回使用JSON对象解析的承诺. -
text()
-返回以USVString(文本)解析的承诺.
clone()
- Creates a clone of a Response object.error()
- Returns a new Response object associated with a network error.redirect()
- Creates a new response with a different URL.arrayBuffer()
- Returns a promise that resolves with an ArrayBuffer.blob()
- Returns a promise that resolves with a Blob.formData()
- Returns a promise that resolves with a FormData object.json()
- Returns a promise that resolves with a JSON object.text()
- Returns a promise that resolves with a USVString (text).
它还允许您将内容发送到服务器,或添加自己的标头等.
It also allows you to send things to the server, or add your own headers etc.
fetch('www.testSite', {
method : 'post',
headers : new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
}),
body : new FormData(document.getElementById('myform'))
}).then( response => {
return response.json(); // server returned valid JSON
}).then( parsed_result => {
console.log(parsed_result);
});
这篇关于提取与AjaxCall的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文