0
你能幫我請把ajax code整合到for循環中嗎?使用循環的Ajax請求
我想從具有類「鏈接」的元素獲取href,然後使用它們製作httpRequests。
我已經看到與螢火蟲,httpRequests發送,我認爲問題是在alertContents函數somwere。 我一整天都在掙扎,但沒有結果。
<a class="links" href="/1">Link1</a>
<a class="links" href="/2">Link2</a>
<a class="links" href="/3">Link3</a>
<script>
for(var i = 0; i < 2; i++) {
makeRequest(document.getElementsByClassName("links")[i].href);
}
function makeRequest(url) {
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :(Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', url);
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
// here i get the final value of the variable i
} else {
alert('There was a problem with the request.');
}
}
}
</script>
全局變量是您的問題的開始。 – epascarello 2014-12-03 20:26:57
@epascarello,你有時間解釋我嗎? – Marian07 2014-12-03 20:29:09
httpRequest = new XMLHttpRequest(); < - 全局,每個循環都被覆蓋。 'XMLHttpRequest'是異步的,它不會等待。因此你有這個問題。 – epascarello 2014-12-03 20:32:01