AJAX is coming back in the wrong order

99封情书 提交于 2019-12-06 15:34:52

Ajax is not guaranteed to finish in the same order that you request them because the server may take longer to return one request than it does the next. to solve this, wait until they are all done, then loop over the original collection and append the results. Below is how you could do that with deferred objects.

var ChatList = new Array();
var p;
var DirectoryList = new Array();
var ChatString = '';

function loadChat(variable) {
    var req = new XMLHttpRequest();
    req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
            DirectoryList = JSON.parse(req.responseText);
            var p = variable;
            var defArr = []; // store references to deferred objects
            while (p < DirectoryList.length) {
                defArr.push(loadLog(p));
                p++;
            }
            $.when.apply($,defArr).done(function(){ // apply handler when all are done
                // handle case where only one ajax request was sent
                var args = arguments;
                if ($.type(args[0]) != "array") {
                    args = [];
                    args[0] = arguments;
                }
                // loop over and ouput results.
                var outHTML = "";
                $.each(args,function(i){
                    outHTML += args[i][0];
                    ChatList.push(args[i][0]);
                });
                $("#ChatContainer").append(outHTML);
            });
        }
    }

    //END REQ1

    //Post Chat to DIV

    function loadLog(p) {
        return $.get('chat/log/' + DirectoryList[p]);
    }

    //End
    req.open('GET', 'process/ReadChatLogs.php', true)
    req.send(null);
}

Edit: fixed case where only one ajax request is sent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!