从循环中进行许多AJAX调用

时间:2014-08-25 16:46:23

标签: javascript jquery ajax

我有一个网页,在提交时,会向我们的数据库添加无限数量的项目。为了避免由于提交的项目太多而导致超时,我想使用jQuery和AJAX调用来代替Web服务。

我试图弄清楚如何编写我的循环以进行这些AJAX调用,以便A)允许多线程并且B)不会挂起浏览器。

简单的外观可能看起来像这样:

elementsToProcess.each(function() {
    // TODO: Submit AJAX call for this element
});

但这是否会挂起浏览器,是否允许多线程?

感谢您的任何提示。

1 个答案:

答案 0 :(得分:1)

我相信这个例子展示了你的要求:

var filesSelected = document.getElementById("privateDocs").files;

var progressholders = document.getElementsByClassName("progressholders");

for(var i=0; i<filesSelected.length; i++) {

    var p = document.createElement("progress");
        p.value = "0";
        p.max = "100";

    var t = document.createElement("span");

    progressholders[i].innerHTML = "";  
    progressholders[i].appendChild(p);
    progressholders[i].appendChild(t);          

    var formData = new FormData();
        formData.append('file', filesSelected[i], filesSelected[i].name);

    UploadDocToServer("upload.php", formData, p, t);                    
}       

实际的ajax功能

function UploadDocToServer (formUrl, formData, progressBar, totalBar) {
  var parent = progressBar.parentNode;

  var ajaxRequest = new XMLHttpRequest();
    ajaxRequest.upload.addEventListener("progress", function(event) {
            totalBar.innerHTML = event.loaded + "bytes of " + event.total + "bytes";
            var percent = (event.loaded / event.total) * 100;
            progressBar.value = Math.round(percent);

        }, false);
    ajaxRequest.addEventListener("load", function(event) {
        progressBar.parentNode.removeChild(progressBar);

        var info = document.createElement("span");
        info.innerHTML = event.target.responseText
        parent.appendChild(info);

    }, false);

    ajaxRequest.addEventListener("error", function() {
        progressBar.parentNode.removeChild(progressBar);

        var info = document.createElement("span");
            info.innerHTML = "Erorr Uploading.";

        parent.appendChild(info);
    }, false);

    ajaxRequest.addEventListener("abort", function() {
        progressBar.parentNode.removeChild(progressBar);

        var info = document.createElement("span");
            info.innerHTML = "Abort called.";

        parent.appendChild(info);
    }, false);

ajaxRequest.open("POST", formUrl);
ajaxRequest.send(formData);

}