簡體   English   中英

ES6 Vanilla JavaScript中的Ajax請求

[英]Ajax request in es6 vanilla javascript

我可以使用jquery和es5發出ajax請求,但我想轉換代碼以使其有效並使用es6。 該請求將如何變化。 (注意:我正在查詢Wikipedia的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")
    }

可能您將使用訪存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

}

如今,您無需使用jQuery或任何API。 就像這樣簡單:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
    console.log(this.responseText);
  }
};
xmlhttp.open('GET', 'https://www.example.com');
xmlhttp.send();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM