es6 vanilla javascript中的Ajax请求

sac*_*ora 8 javascript api ajax jquery ecmascript-6

我能够使用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")
    }
Run Code Online (Sandbox Code Playgroud)

ter*_*osa 19

您可能会使用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")
    });
Run Code Online (Sandbox Code Playgroud)

如果你想做异步,那是不可能的.但是你可以看起来不像Async-Await功能的异步操作.

  • 如果您没有设置原始标题,将会出现CORS错误 (3认同)