JavaScript的:XHR不能处理多个异步请求 [英] Javascript: XHR not handling multiple async requests

查看:522
本文介绍了JavaScript的:XHR不能处理多个异步请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我试图访问一个资源多次使用不同的参数

Hi I am trying to access one resource multiple times with with different parameters

在这种情况下,要求

    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);
    }

但是,只有一个请求的正在由code拉姆达处理。铬报道说,这两项要求已收到,并可见在资源匮乏的窗格中。

However, only one of of the requests is being handled by the code lambda. Chromium reports that both requests have been received and is viewable in the resourced pane.

另外,如果我提出请求同步然后正常工作。然而,这是不能接受的释放code作为请求可能超时。

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.

感谢

推荐答案

定义 HTTP_REQUEST 使用 VAR 。目前,你分配XHR对象的全局变量。正因为如此,你的脚本可以一次只能处理一个XHR。

Define http_request using var. Currently, you're assigning the XHR object to a global variable. Because of this, your script can only handle one XHR at a time.

相关错误code:

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

建议更改:

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

当你省略 VAR 变量之前,变量将在全球进行定义(窗口)范围。如果你使用 VAR 变量之前,该变量在本地范围内定义(函数要求,在这种情况下, )。

When you omit var before a variable, the variable will be defined in the global (window) scope. If you use var before a variable, the variable is defined within the local scope (in function request, in this case).

这篇关于JavaScript的:XHR不能处理多个异步请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆