Javascript 需要2个函数才能在Ajax上运行onLoad-只有1个可以工作

Javascript 需要2个函数才能在Ajax上运行onLoad-只有1个可以工作,javascript,ajax,onload,Javascript,Ajax,Onload,从洗牌函数开始(只是洗牌数组)。它起作用了。 然后我定义了两个全局变量,它们将决定页面上显示图像的随机顺序。 picOrder将是一个从0到picCount的简单数组,picCount由Ajax onload确定。正在检索picCount,但未设置picOrder数组!如果我在控制台中手动运行“arrangePics();”,它就会工作。它按picOrder填充数组,然后洗牌。但是,将对这两个函数的调用放在“”中或将“doStuff()”函数放在其中都不起作用 Array.prototype.s

从洗牌函数开始(只是洗牌数组)。它起作用了。 然后我定义了两个全局变量,它们将决定页面上显示图像的随机顺序。 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);
}
Array.prototype.shuffle=function(){
var s=[];
而(this.length)s.push(this.splice(Math.random()*this.length,1)[0]);
而(s.length)这个.push(s.pop());
归还这个;
}
var picOrder=新数组();
var picCount;
函数getPicCount(){
//picCount=阵列(10);
if(window.XMLHttpRequest){//IE7+、Firefox、Chrome、Opera、Safari的代码
xmlhttp=新的XMLHttpRequest();
}else{//IE6、IE5的代码
xmlhttp=新的ActiveXObject(“Microsoft.xmlhttp”);
}
xmlhttp.onreadystatechange=函数(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
picCount=xmlhttp.responseText;
}
}
open(“GET”,“/example.com/images.php?count=hello”,true);
xmlhttp.send();
//picCount.shuffle;
}
函数排列pics(){

对于(var i=0;i,您需要在异步AJAX调用返回后
arrangePics()
,即,您只能在
中调用它,如果(xmlhttp.readyState==4&&xmlhttp.status==200){}
(回调)块,否则您无法确保数据已完全接收

当前发生的情况是JavaScript正在调用
getPicCount();arrangePics();
-第一个方法启动AJAX调用并立即返回,然后第二个方法将尝试排列0个pics。执行
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();
}
if(xmlhttp.readyState==4&&xmlhttp.status==200){
picCount=xmlhttp.responseText;
对于(var i=0;i
<body onLoad="doStuff();">
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    picCount = xmlhttp.responseText;

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