【问题标题】:Ajax request in es6 vanilla javascriptes6 vanilla javascript中的Ajax请求
【发布时间】:2018-06-03 01:13:19
【问题描述】:

我可以使用 jquery 和 es5 发出 ajax 请求,但我想转换我的代码,以便它的 vanilla 和使用 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")
    }

【问题讨论】:

  • XMLHttpRequest .... 或者 fetch ... 你自己决定... 顺便说一句,这真的与 ES5 vs ES6 无关
  • 两者都可以。但我更喜欢 fetch。
  • Either would be fine. But I would prefer fetch - 然后这样做
  • 维基百科 API 看起来不需要 JSONP 请求。只需一个简单的 JSON 请求即可。

标签: javascript jquery ajax api ecmascript-6


【解决方案1】:

你可能会使用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 功能使其看起来不像异步操作。

【讨论】:

    【解决方案2】:

    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
    
    }
    

    【讨论】:

      【解决方案3】:

      现在您不需要使用 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();
      

      【讨论】:

      猜你喜欢
      • 2020-01-18
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多