2013-11-04 91 views
0

我試圖使幾個(在下面的例子中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次。

有人可以解釋爲什麼嗎?

+0

可能重複[並行ajax調用 - 無法從第一個接收響應](http://stackoverflow.com/questions/19765590/parallel-ajax-calls-fail-to-receive-response-from -the-first) –

回答

2

你正在墮入The Horror of Implicit Globals。這條線:

xhr = new XMLHttpRequest(); 

創建/設置了全球變量,而不是本地的。所以發生的是每次你調用這個函數時,你都覆蓋了以前的值xhr

爲了使其在功能本地化,請在其前面放置var。您還必須將需要訪問該變量的函數轉換爲load函數,以便它們關閉它。 (別擔心,closures are not complicated。)


令人驚訝的是,這isn't even the first time today我已經回答了這個。 :-)

+0

非常感謝,男:) – Anton