我已经使用JQuery很久了,我熟悉其中的AJAX-Calls。我经常遇到这样的情况,我不得不等到多个请求完成后再继续执行,直到获得结果。
JQuery语法如下:
$.when(
$.ajax({
type: "POST",
url: '/Services/Service.asmx/GetResults1',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
...
},
error: function (e) {
console.log('ERROR! ' + e.responseText);
}
}),
$.ajax({
type: "POST",
url: '/Services/Service.asmx/GetResults2',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
...
});
},
error: function (e) {
console.log('ERROR! ' + e.responseText);
}
})
).done(function (result1, result2) {
// Do s.th. with result1 and result2 what is already
// available here
updateUI();
...
});
如何在VanillaJS中做到这一点?
答案 0 :(得分:0)
以下是使用新的香草JS提取API的示例
fetch('URL', {
method: "POST/PUT/GET/DELETE",
body: JSON.stringify({
name: Name,
otherData : otherData
}),`enter code here`
headers: {"content-type": "application/json"}
})
.then(res => res.json())
.then(response => {
//do what you want with the response here
})
对于GET请求,您可以以类似方式退出主体
fetch('URL', {
method: "GET",
headers: {"content-type": "application/json"}
})
.then(res => res.json())
.then(response => {
//do what you want with the response here
})
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
document.getElementById("userID").innerHTML = json.userId;
document.getElementById("title").innerHTML = json.title;
document.getElementById("completed").innerHTML= json.completed;
})
<div>The User ID is : </div>
<div id="userID">
</div>
<div>The Title is : </div>
<div id="title">
</div>
<div>Completed : </div>
<div id="completed">
</div>
答案 1 :(得分:0)
将此内容与您的AJAX请求进行比较:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
receivedJSON = JSON.parse(xhttp.responseText);
//Your success: function here...
}else{
//Your error: function here...
}
};
xhttp.open("POST","/Services/Service.asmx/GetResults1",true);
xhttp.send(/**Your JSON Data**/);