目前,我正在尝试动态填充网站。当我逐步执行代码时,它可以完美工作。但是,当我按预期在页面加载时运行它时,它不起作用。相关代码为:
<body onload="populate_all(string)";>
function populate_all(string)
{
var split = string.split(" ");
for(i = 0; i < split.length; i++)
{
populate(split[i], 'main');
}
}
function populate(string, location)
{
if (string.length==0)
{
document.getElementById(location).innerHTML="";
return;
}
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)
{
var divTag = document.createElement("div");
divTag.className ="info";
divTag.innerHTML = xmlhttp.responseText;
document.getElementById(location).appendChild(divTag);
}
}
xmlhttp.open("GET","populate.php?string="+string,true);
xmlhttp.send();
}
我已经阅读了足够的有关此问题的内容,可以确定php不是问题。基本上:我在AJAX中循环运行了一次javascript函数,并且该代码仅在调试时有效。谢谢您的帮助!
最佳答案
Declare xmlhttp
本地。
使用其他变量名称作为location
。 location
是全局变量,其中包含用于操纵当前位置的属性和方法。
function populate(string, s_location) {
var xmlhttp;
当前,您一直在覆盖
xmlhttp
方法中的populate
变量。结果,xmlhttp
对象指向最后一个请求。关于javascript - Javascript/AJAX仅在调试时有效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10063481/