我正在尝试同时制作少量(以下示例中为3个)ajax调用。 在doOnload(由onload事件触发)中,我使用不同的参数调用函数load。
以下是代码:
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次。
有人可以解释原因吗?
答案 0 :(得分:2)
你正在成为The Horror of Implicit Globals的牺牲品。这一行:
xhr = new XMLHttpRequest();
创建/设置全局变量,而不是本地变量。所以发生的事情是每次调用函数时,你都会覆盖xhr
之前的值。
要使其成为函数的本地函数,请将var
放在其前面。您还必须将需要访问该变量的函数移动到 load
函数中,以便它们关闭它。 (别担心,closures are not complicated。)
令人惊讶的是,这isn't even the first time today我已经回答了这个问题。 : - )