我有这段代码,应该在循环的每次迭代中发送请求,但它在最后一次迭代中运行,为什么?
function findTotal(){
var arr = document.getElementsByName('price');
var PID = document.getElementsByName('product');
var tot = 0;
var xml ;
for ( j=0; j<PID.length; j++){
xml = new XMLHttpRequest();
xml.onreadystatechange=function()
{
if (xml.readyState==4 && xml.status==200){
for( i=0;i<arr.length;i++){
if(parseInt(arr[i].value)){
tot += xml.responseText * arr[i].value;
document.getElementById('total').value = tot;
}
}
}
}
xml.open("POST","http://localhost/CRM/mr/getPrice/"+PID[j].value);
xml.send();
}
}
您一遍又一遍地为一个xml
对象设置onstatechange
,您希望为每次迭代创建一个新的xml
对象。将xml = new XMLHttpRequest();
语句移到for
循环中
您应该为每个请求使用一个新的XMLHttpRequest对象,因为前一个请求很可能还没有完成。
open ()
…
注意:对于已经激活的请求(其中open()或openRequest()已经被调用)调用此方法相当于调用abort()。
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest open ()