Dar*_*lyn 37 javascript ajax fetch-api
典型的AJAX和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
Run Code Online (Sandbox Code Playgroud)
这是fetch调用返回的内容:
Response {type: "cors", url: "www.testSite", status: 200, ok: true, statusText: "OK"…}
Run Code Online (Sandbox Code Playgroud)
为什么它会返回不同的东西?
有没有办法fetch返回与典型的AJAX调用相同的东西?
ade*_*neo 37
Fetch API内置了不同数据类型的方法.
对于常规的text/html,您将使用该text()方法,该方法也返回一个promise,然后将其链接到另一个然后调用.
fetch('www.testSite').then( x => {
return x.text();
}).then( y => {
console.log(y);
});
Run Code Online (Sandbox Code Playgroud)
返回内容的内置函数如下
它还允许您将内容发送到服务器,或添加自己的标题等.
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);
});
Run Code Online (Sandbox Code Playgroud)
您的ajaxCall从XMLHttpRequest对象返回responseText.它正在过滤掉它.
您需要在获取代码中读取响应文本.
fetch('/foo/').then( x => return x.text() } ).then(text => console.log(text))
Run Code Online (Sandbox Code Playgroud)
你也可以使用x.json()或x.blob()
| 归档时间: |
|
| 查看次数: |
27721 次 |
| 最近记录: |