简体   繁体   English

Javascript:XHR不处理多个异步请求

[英]Javascript: XHR not handling multiple async requests

Hi I am trying to access one resource multiple times with with different parameters 嗨,我尝试使用不同的参数多次访问一种资源

In this case requesting 在这种情况下

    var domains = [
    'host1',
    'host2'
    ];

    var requests = new Array();

    for ( i in domains )
    {
        requests[i]=new request(domains[i]);
    }

    function request(site)
    {
        var url = 'get_remote_status.php?host='+site;
        var queues = {};
        http_request = new XMLHttpRequest();
        http_request.open("GET", url, true, 'username', 'password');
        http_request.onreadystatechange = function () {
            var done = 4, ok = 200;
            if (http_request.readyState == done && http_request.status == ok) {
                queues = JSON.parse(http_request.responseText);
                var queuesDiv = document.getElementById('queues');
                print_queues(queues, queuesDiv, site);              
            }
        };
        http_request.send(null);
    }

However, only one of of the requests is being handled by the code lambda. 但是,代码lambda只处理其中一个请求。 Chromium reports that both requests have been received and is viewable in the resourced pane. Chromium报告已收到两个请求,并且可以在资源窗格中查看它们。

Also if I make the request synchronous then it works fine. 另外,如果我使请求同步,那么它可以正常工作。 However this is not acceptable to the release code as a request may timeout. 但是,这对于发布代码是不可接受的,因为请求可能会超时。

Thanks 谢谢

Define http_request using var . 使用var定义http_request Currently, you're assigning the XHR object to a global variable. 当前,您正在将XHR对象分配给全局变量。 Because of this, your script can only handle one XHR at a time. 因此,您的脚本一次只能处理一个XHR。

Relevant erroneous code: 相关错误代码:

function request(site)
{
    var url = 'get_remote_status.php?host='+site;
    var queues = {};
    http_request = new XMLHttpRequest();

Proposed change: 拟议的变更:

function request(site)
{
    var url = 'get_remote_status.php?host='+site;
    var queues = {};
    var http_request = new XMLHttpRequest(); //VAR VAR VAR !!!

When you omit var before a variable, the variable will be defined in the global ( window ) scope. 当您在变量前省略var ,该变量将在全局( window )范围内定义。 If you use var before a variable, the variable is defined within the local scope (in function request , in this case). 如果在变量之前使用var ,则该变量在本地范围内定义(在这种情况下,在function request中)。

In fact it is possible to run multiple async xhr call but you have to give them an unique id as parameter to be able to store and load them locally in your DOM. 实际上,可以运行多个异步xhr调用,但是您必须给它们指定一个唯一的id作为参数,以便能够在DOM中本地存储和加载它们。

For example, you'd like to loop on an array and make a ajax call for each object. 例如,您想在数组上循环并为每个对象进行ajax调用。 It's a little bit tricky but this code works for me. 有点棘手,但是这段代码对我有用。

var xhrarray={};
for (var j=0; j<itemsvals.length; j++){
                var labelval=itemsvals[j];
                // call ajax list if present.
                if(typeof labelval.mkdajaxlink != 'undefined'){
                    var divlabelvalue = '<div id="' + labelval.mkdid + '_' +          item.mkdcck + '" class="mkditemvalue col-xs-12 ' + labelval.mkdclass + '"><div class="mkdlabel">' + labelval.mkdlabel + ' :</div><div id="'+ j +'_link_'+ labelval.mkdid +'" class="mkdvalue">'+labelval.mkdvalue+'</div></div>';
                    mkdwrapper.find('#' + item.mkdcck + ' .mkdinstadivbody').append(divlabelvalue);

                    xhrarray['xhr_'+item.mkdcck] = new XMLHttpRequest();
                    xhrarray['xhr_'+item.mkdcck].uniqueid=''+ j +'_link_'+ labelval.mkdid +'';
                    console.log(xhrarray['xhr_'+item.mkdcck].uniqueid);
                    xhrarray['xhr_'+item.mkdcck].open('POST', labelval.mkdajaxlink);
                    xhrarray['xhr_'+item.mkdcck].send();
                    console.log('data sent');
                    xhrarray['xhr_'+item.mkdcck].onreadystatechange=function() {
                        if (this.readyState == 4) {
                            console.log(''+this.uniqueid);
                            document.getElementById(''+this.uniqueid).innerHTML = this.responseText;
                        }
                    };
                }
}

You have to set each xhr object in a global variable object and define a value xhrarray['xhr_'+item.mkdcck].uniqueid to get its unique id and load its result where you want. 您必须在全局变量对象中设置每个xhr对象,并定义一个值xhrarray['xhr_'+item.mkdcck].uniqueid以获取其唯一ID,并将其结果加载到所需的位置。

Hope that will help you in the future. 希望将来对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM