2011-12-16 50 views
1

從shuffle函數開始(只需洗牌數組)。有用。 然後,我定義了2個全局變量,它們將確定要在頁面上顯示的圖像的隨機順序。 picOrder將是一個從0到picCount的簡單數組,picCount由Ajax onload決定。正在檢索picCount,但未設置picOrder數組!如果我手動運行「arrangePics();」在它的控制檯中工作。它填充數組picOrder,然後洗牌。但是,通過將調用放在「」中的這兩個函數或將「doStuff()」函數放在那裏不起作用。需要2個函數在Ajax上運行onLoad - 只有1個工作

Array.prototype.shuffle = function() { 
var s = []; 
while (this.length) s.push(this.splice(Math.random() * this.length, 1)[0]); 
while (s.length) this.push(s.pop()); 
return this; 
} 

var picOrder = new Array(); 
var picCount; 

function getPicCount() { 
// picCount = array(10); 
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
     } else {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
    xmlhttp.onreadystatechange=function() { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) { 
      picCount = xmlhttp.responseText; 
     } 
     } 
    xmlhttp.open("GET","/example.com/images.php?count=hello",true); 
    xmlhttp.send(); 
    //picCount.shuffle; 

} 

function arrangePics() { 
    for(var i = 0;i<picCount;i++) { 
    picOrder[i] = i; 
    } 
    picOrder.shuffle(); 
    //alert(picOrder); 
} 

HTML

<body onLoad="getPicCount();arrangePics();"> 

<body onLoad="doStuff();"> 

回答

0

您需要arrangePics()後的異步AJAX調用返回,也就是說,你只能把它在if (xmlhttp.readyState==4 && xmlhttp.status==200) {}(回調)塊否則您無法確定數據是否已完全收到。

目前發生的事情是JavaScript調用getPicCount();arrangePics(); - 第一種方法啓動AJAX調用並立即返回,然後第二種方法將嘗試排列0個圖片。在控制檯上手動執行arrangePics()會在系統中引入足夠的延遲以完成AJAX調用,並且picCount將按預期設置。

所以,如果你改變了回調函數:

if (xmlhttp.readyState==4 && xmlhttp.status==200) { 
    picCount = xmlhttp.responseText; 

    for(var i = 0;i<picCount;i++) { 
     picOrder[i] = i; 
    } 
    picOrder.shuffle(); 
} 

應該洗牌圖片的數量已經被接收了。

相關問題