2017-12-20 4 views
1

Ich bin in der Lage, eine Ajax-Anfrage mit jquery und es5 zu machen, aber ich möchte mich Code ändern, so dass es Vanille und es6 verwendet. Wie würde sich diese Anfrage ändern? (Hinweis: Ich frage Wikipedia API).Ajax Anfrage in es6 Vanille Javascript

 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") 
    } 
+2

Sie würden die API holen verwenden: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch –

+2

XMLHttpRequest .... oder holen ... Sie entscheiden. Übrigens, das hat wirklich nichts mit ES5 vs ES6 zu tun. –

+0

Entweder wäre in Ordnung. Aber ich würde lieber holen. – sacora

Antwort

0

Wahrscheinlich werden Sie Sie 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") 
    }); 

Wenn Sie async machen wollen, ist es unmöglich. Aber Sie können es nicht als asynchrone Operation mit Async-Await Feature aussehen lassen.

+0

Wird erhalten CORS-Fehler, wenn Sie nicht Herkunft Header setzen – charlietfl

1

AJAX-Anfragen sind nützlich, um Daten asynchron zu senden, eine Antwort zu erhalten, sie zu überprüfen und durch Aktualisierung ihres Inhalts auf die aktuelle Webseite anzuwenden.

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 

}