繁体   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