我試圖使幾個(在下面的例子中3)同時調用ajax。 在doOnload(由onload事件觸發)我用不同的參數調用函數加載。很少有同時ajax請求
下面是代碼:
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次。
有人可以解釋爲什麼嗎?
可能重複[並行ajax調用 - 無法從第一個接收響應](http://stackoverflow.com/questions/19765590/parallel-ajax-calls-fail-to-receive-response-from -the-first) –