javascript es6 vanilla javascript中的Ajax请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47906665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:41:27  来源:igfitidea点击:

Ajax request in es6 vanilla javascript

javascriptjqueryajaxapiecmascript-6

提问by sacora

I am able to make an ajax request using jquery and es5 but I want to transition me code so that its vanilla and uses es6. How would this request change. (Note: I am querying Wikipedia's api).

我能够使用 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")
    }

回答by termosa

Probably, you will use fetch API:

可能你会使用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")
    });

If you want to make async, it is impossible. But you can make it look like not async operation with Async-Awaitfeature.

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

回答by Giulio Bambini

AJAX requests are useful to send data asynchronously, get response, check it and apply to current web-page via updating its content.

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

}

回答by daaawx

Nowadays you don't need to use jQuery or any API. It's as simple as doing this:

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