0
我想通過編寫一些基本的API查詢來學習vanilla JS AJAX。但是,我收到請求的狀態爲0
。這是什麼意思,我該如何解決這個問題?XMLHttpRequest狀態在簡單的AJAX調用上返回零
var x = document.getElementsByClassName("btn")
for (var i = 0; i < x.length; i++) {
x[i].addEventListener('click', makeRequest);
}
var httpRequest;
function makeRequest() {
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :(Cannot create an XMLHTTP instance');
return false;
}
document.getElementsByClassName(".text").innerHTML= 'Loading Data ... '
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', 'https://api.meetup.com/2/cities');
httpRequest.send(null);
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.' + httpRequest.status);
}
}
}
}
下面的jQuery代碼完成這項工作。我仍然很好奇爲什麼上面的代碼不起作用。
$('.btn').click(function(){
$('.text').text('Loading data . . . ');
$.ajax({
type: "GET",
url: 'https://api.meetup.com/2/cities',
success: function(data) {
$('.text').text(JSON.stringify(data));
},
dataType: "jsonp",
})
});
你點擊了什麼來撥打電話? – epascarello
帶'btn'類的按鈕 – MadPhysicist
我得到了這個錯誤'alert('請求有問題'+ httpRequest.status);' – MadPhysicist