AJAX-запрос в ES6 в ванили на JavaScript



Я могу сделать запрос ajax, используя jquery и es5, но я хочу передать мне код так, чтобы его ваниль и использует es6. Как изменится эта просьба? (Примечание: я запрашиваю api Википедии).



      var link = "https://en.wikipedia.org/w/api.php?action=query&prop=info&pageids="+ page +"&format=json&callback=?";

$.ajax({
type: "GET",
url: link,
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success:function(re){
},
error:function(u){
console.log("u")
alert("sorry, there are no results for your search")
}
563   2  

2 ответов:

Вероятно, вы будете вам 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")
    });

Если вы хотите сделать асинхронным, это невозможно. Но вы можете сделать так, чтобы это выглядело как не асинхронная операция с функцией Async-Await.

Запросы AJAX полезны для асинхронной отправки данных, получения ответа, проверки его и применения к текущей веб-странице путем обновления ее содержимого.

function ajaxRequest()
{
    var link = "https://en.wikipedia.org/w/api.php?action=query&prop=info&pageids="+ page +"&format=json&callback=?";
    var xmlHttp = new XMLHttpRequest(); // 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

}

Comments

    Ничего не найдено.