es6 vanilla javascript 中的 Ajax 请求

新手上路,请多包涵

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

原文由 sacora 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 316
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")
    });

如果你想让 not async ,那是不可能的。但是您可以使用 Async-Await 功能使其看起来不像异步操作。

原文由 termosa 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

}

原文由 Giulio Bambini 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏