es6 vanilla javascript中的Ajax请求 [英] Ajax request in es6 vanilla javascript

查看:21
本文介绍了es6 vanilla javascript中的Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够使用 jquery 和 es5 发出 ajax 请求,但我想转换我的代码,以便它的 vanilla 并使用 es6.此请求将如何更改.(注意:我正在查询维基百科的 api).

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).

      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 功能使其看起来不像异步操作.

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

这篇关于es6 vanilla javascript中的Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆