为什么XMLHTTPRequest在ajax循环的最后一次迭代中运行


Why the XMLHTTPRequest run in last iteration of loop ajax

我有这段代码,应该在循环的每次迭代中发送请求,但它在最后一次迭代中运行,为什么?

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 ()