请帮助我将此ajax code整合到for循环中吗?
我试图从带有“链接”类的元素中获取href,然后使用它们
制作httpRequests。
我用firebug看过,httpRequests被发送了,我认为问题在alertContents函数中是个问题。
我整天都在挣扎,但没有结果。
<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>
答案 0 :(得分:0)
我声明了变量,因此它不是全局的,并且在makeRequest函数中移动了你的回调函数。
for (var i = 0; i < 2; i++) {
makeRequest(document.getElementsByClassName("links")[i].href);
}
function makeRequest(url) {
var httpRequest;
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.');
}
}
}
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();
}