我能够使用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")
}
答案 0 :(得分:13)
您可能会使用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")
});
如果你想制作 async ,那是不可能的。但是你可以使用Async-Await功能看起来不像异步操作。
答案 1 :(得分:1)
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
}
答案 2 :(得分:0)
如今,您无需使用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();