Rom*_*cle 8 javascript ajax jquery
我正在尝试将我的API调用从使用jQuery ajax迁移到使用Fetch API.
我在服务器调用期间使用jQuery ajaxStart和ajaxStop来显示加载微调器.
我正在运行多个并行服务器请求,我希望微调器在第一个请求启动时启动,并在最后一个请求结束时停止.
这与jQuery相当直接.但是,我找不到使用fetch API的类似技术.有任何想法吗 ?
您可以用来Promise通知何时fetch调用并完成
var params = {
a: 1,
b: 2
};
var data = new FormData();
data.append("json", JSON.stringify(params));
var currentRequest = new Request("/echo/json/", {
method: "POST",
body: data
});
var start, complete;
var fetchStart = new Promise(function(_start) {
start = _start;
})
var fetchComplete = new Promise(function(_complete) {
complete = _complete;
});
// do stuff when `fetch` is called
fetchStart.then(function(startData) {
console.log(startData)
});
// do stuff when `fetch` completes
fetchComplete.then(function(completeData) {
console.log(completeData)
});
var request = fetch(currentRequest);
[request, start({
"fetchStarted": currentRequest
})].shift()
.then(function(res) {
if (res.ok) {
// resolve `fetchComplete` `Promise` when `fetch` completes
complete({
"fetchCompleted": res
})
};
return res.json();
})
.then(function(data) {
document.body.textContent = JSON.stringify(data)
})
.catch(function(err) {
// if error, pass error to `fetchComplete`
complete({
"fetchCompleted": res,
"error": err
});
});
Run Code Online (Sandbox Code Playgroud)
jsfiddle https://jsfiddle.net/abbpbah4/18/
另请参阅获取:POST json 数据