0

我正在尝试同时进行少量(以下示例中为 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 次。

有人可以解释为什么吗?

4

1 回答 1

2

You're falling prey to The Horror of Implicit Globals. This line:

xhr = new XMLHttpRequest();

creates/sets a global variable, not a local one. So what's happening is that each time you call the function, you're overwriting the previous value of xhr.

To make it local to the function, put var in front of it. You'll also have to move the functions that require access to that variable into the load function, so they close over it. (Don't worry, closures are not complicated.)


Astonishingly, this isn't even the first time today I've answered this. :-)

于 2013-11-04T14:33:55.203 回答