ES6 Vanilla JavaScript中的Ajax请求 [英] Ajax request in es6 vanilla javascript
问题描述
我能够使用jquery和es5发出ajax请求,但我想对我的代码进行转换,以使其原始版本和使用es6.该请求将如何变化. (注意:我正在查询Wikipedia的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")
}
可能您将使用 如果要进行异步,则不可能.但是您可以使用异步等待功能使它看起来像不是异步操作./p> 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).
Probably, you will use fetch API: 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屋! 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")
}
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")
});