I have used JQuery since a long time and i am familar with the AJAX-Calls in it. I often had the situation where i had to wait until multiple requests have been finished and continue after that with the results.
The JQuery syntax was the following:
$.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();
...
});
How can you do this in VanillaJS?
Here is an example using the new vanilla JS fetch 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
})
For a GET request you can opt-out the body in fetch like
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>
Compare this one with your AJAX request:
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**/);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.