我是ajax新手,已经学了一些w3 schools在线课程。现在我已经可以在网站上加载内容了,但是当加载发生时,只会向用户显示一个加载图像。我在网上搜了很久也发现了一些相同的问题,但他们使用的是其他类型的Ajax,这是我所不知道的。
我的代码:
<script>
function loadXMLDoc(a)
{
var xmlhttp;
var temp = "myname.php?id=" + a;
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",temp,true);
xmlhttp.send();
}
</script>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc('1')">Request 1</button>
<button type="button" onclick="loadXMLDoc('2')">Request 2</button>
<button type="button" onclick="loadXMLDoc('3')">Request 3</button>
<div id="myDiv"></div>
如果有人可以根据我的编码给我一个例子或链接,将不胜感激。
Create an <img>
element that is hidden to begin with, then when the ajax is called, show it, and when completed, hide it.
<script>
function loadXMLDoc(a)
{
var xmlhttp;
var temp = "myname.php?id=" + a;
// show the loading image
document.getElementById("loading").style.display = "";
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)
{
// hide the loading image
document.getElementById("loading").style.display = "none";
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",temp,true);
xmlhttp.send();
}
</script>
<h2>AJAX</h2>
<img src="loading.gif" alt="Loading..." id="loading" style="display:none;" />
<button type="button" onclick="loadXMLDoc('1')">Request 1</button>
<button type="button" onclick="loadXMLDoc('2')">Request 2</button>
<button type="button" onclick="loadXMLDoc('3')">Request 3</button>
<div id="myDiv"></div>
For future reference, the Mozilla Development Network docs are a good resource for plain Javascript ajax.
1) add a loading animation image (img tag) in the HTML document and place it where you want to display, but you hide it with CSS by setting display: none
2) before your xmlhttp.send(), show the image by setting the image display: ''
3) in the xmlhttp.onreadystatechange
callback function, hide the image again to indicate the loading is finished.