从洗牌函数开始(只是洗牌数组)。它的工作原理。然后我定义了2个全局变量,它们将决定页面上显示图像的随机顺序。picOrder将是一个从0到picCount的简单数组,其中picCount由Ajax onload决定。正在检索picCount,但是没有设置picOrder数组!如果我在控制台中手动运行"arrangePics();",它就能工作。它填充数组picOrder,然后对其进行洗牌。但是,如果将对两个函数的调用都放在"中,或者将"doStuff()"函数放在那里,则无法工作。
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();">
您需要在异步AJAX调用返回后arrangePics()
,即您只能在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();
}
它应该在收到计数后对图片进行洗牌。