【问题标题】:Few simultaneously ajax requests很少同时 ajax 请求
【发布时间】:2013-11-04 22:33:55
【问题描述】:

我正在尝试同时进行少量(以下示例中为 3 个)ajax 调用。 在 doOnload(由 onload 事件触发)中,我使用不同的参数调用函数加载。

代码如下:

function doOnload()
{
    load(0, 10);
    load(10, 10);
    load(20, 10);
}

function load(offset, length)
{
    xhr = new XMLHttpRequest();
    xhr.offset = offset;

    var nocache = '&token=' + Math.random();

    url = 'load.php?offset=' + offset + '&length=' + length + nocache;

    xhr.onreadystatechange = process_request_status_change;
    xhr.open("GET", url, true);
    xhr.send(null);
}

function process_response()
{
    var div;
    var json = JSON.parse(xhr.responseText);
    var main = document.getElementById('main');

    for(var i = 0; i < json.length; i++)
    {
        div = document.createElement('div');
        div.innerHTML = json[i];
        main.appendChild(div);

        main.appendChild(document.createTextNode("\n"));
    }
}

function process_request_status_change()
{
    if (xhr.readyState === 4)
    {
        if (xhr.status === 200)
        {
            process_response();
        }
        else
        {
            console.log('%c Server side issue', 'color: red;');
        }
    }
}

load.php的代码:

$list = range(0, 1000);

$offset = isset($_GET['offset'])    ? $_GET['offset']   : 0;
$length = isset($_GET['length'])    ? $_GET['length']   : sizeof($list);

header("Content-type: application/json");
echo json_encode(array_slice($list, $offset, $length));

预期行为: 将(以随机顺序)添加到 10 个 div 标签中的主要元素 3 个序列

实际行为: 在 html 代码中只添加最后一个序列,但可以添加 1、3 或 7 次。

谁能解释一下原因?

【问题讨论】:

标签: javascript ajax


【解决方案1】:

你正在成为The Horror of Implicit Globals 的牺牲品。这一行:

xhr = new XMLHttpRequest();

创建/设置一个全局变量,而不是本地变量。所以发生的情况是,每次调用函数时,都会覆盖 xhr 的先前值。

要使其成为函数的局部变量,请将var 放在它前面。您还必须将需要访问该变量的函数移入load 函数,以便它们关闭它。 (别担心,closures are not complicated。)


令人惊讶的是,isn't even the first time today 我已经回答了这个问题。 :-)

【讨论】:

    猜你喜欢
    • 2011-11-28
    • 2013-01-21
    • 2017-03-04
    • 1970-01-01
    • 2013-08-02
    • 2019-06-24
    • 2014-10-11
    • 1970-01-01
    相关资源
    最近更新 更多