Ajax Request In Es6 Vanilla Javascript
I am able to make an ajax request using jquery and es5 but I want to transition me code so that its vanilla and uses es6. How would this request change. (Note: I am querying Wikipe
Solution 1:
Probably, you will use fetch API:
fetch(link, { headers: { "Content-Type": "application/json; charset=utf-8" }})
.then(res => res.json()) // parse response as JSON (can be res.text() for plain response)
.then(response => {
// here you do what you want with response
})
.catch(err => {
console.log("u")
alert("sorry, there are no results for your search")
});
If you want to make async, it is impossible. But you can make it look like not async operation with Async-Await feature.
Solution 2:
AJAX requests are useful to send data asynchronously, get response, check it and apply to current web-page via updating its content.
functionajaxRequest()
{
var link = "https://en.wikipedia.org/w/api.php?action=query&prop=info&pageids="+ page +"&format=json&callback=?";
var xmlHttp = newXMLHttpRequest(); // creates 'ajax' object
xmlHttp.onreadystatechange = function() //monitors and waits for response from the server
{
if(xmlHttp.readyState === 4 && xmlHttp.status === 200) //checks if response was with status -> "OK"
{
var re = JSON.parse(xmlHttp.responseText); //gets data and parses it, in this case we know that data type is JSON. if(re["Status"] === "Success")
{//doSomething}else
{
//doSomething
}
}
}
xmlHttp.open("GET", link); //set method and address
xmlHttp.send(); //send data
}
Solution 3:
Nowadays you don't need to use jQuery or any API. It's as simple as doing this:
var xmlhttp = newXMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
}
};
xmlhttp.open('GET', 'https://www.example.com');
xmlhttp.send();
Post a Comment for "Ajax Request In Es6 Vanilla Javascript"