我遇到了一个挑战:
如何使用AJAX在页面上重新加载<div>
,而没有加载栏,并且在加载内容时不会消失。
我想保持以前生成的内容,只要新内容加载。
这是我的脚本,但是当在循环中加载内容时,它会闪烁:
<script type="text/javascript">
function showCargo_34(urlparms)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttpshowCargo_34=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttpshowCargo_34=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpshowCargo_34.onreadystatechange=function()
{
if (xmlhttpshowCargo_34.readyState==4 && xmlhttpshowCargo_34.status==200)
{
document.getElementById("Cargo_34").innerHTML=xmlhttpshowCargo_34.responseText;
}
}
xmlhttpshowCargo_34.open("GET","modules/desktop/desktop/script_cargo.php?"+urlparms,true); // modules/catalogitem/script_categorylist.php?"+urlparms
xmlhttpshowCargo_34.send();
};
</script>
<div id="Cargo_34"></div>
<script>
function repeat_Cargo_34() {
showCargo_34('baseid=1&moduleid=10&gridmoduleid=133&speed=180&x=3&y=4');
setTimeout( repeat_Cargo_34, 20000);
};
repeat_Cargo_34();
</script>
我将使用jquery ajax。这样更快更简单。
简单方法$("#element_id").load("http://url.com");
更高级的方法可以在这里找到
你还说要保留以前的内容。我们只需对innerHTML:
使用+=document.getElementById("Cargo_34").innerHTML += xmlhttpshowCargo_34.responseText;
如果你不想使用jquery,我建议创建第二个ajax函数,并使当前函数更改为不可见的div,当加载和更改完成时,您将返回以下行
//Echo this once all data has been loaded and changed.
//$newurlPalms is what you would have echoed normally but in a urlpalm.
echo "<style onload='showCargo2($newurlpalms)'></style>";
//so make this only load and save all the data and then echo above line in
//a hidden div
function showcargo(urlpalms){ajaxcode}
//make this show the data in the right div.
function showcargo2(urlpalms){ajaxdoce}
像这样的,它不会删除数据,一旦加载完成,echo将导致第二个函数自动运行,它能够立即显示数据。
使用jQuery的AJAX,这更容易。看看load()函数,例如setInterval。例如:
setInterval(function(){ $('#div').load('file.html'); }, 5000}
每5秒它将加载file.html到<div id="id">
这种情况不存在。
解释:
标准的html请求调用,因为它是在我的问题不把innerHTML
的内容,而加载。这意味着当内容被加载时,它将按原样显示,直到内容以JSON格式完成并且ajax调用函数完成。
错误在代码的另一部分