当Ajax获取文件内容时显示加载图像

7

我很新到AJAX,阅读了一些教程以制作一个小脚本,其中有多个按钮,每次单击将在特定的div中加载php文件。为此,我使用以下代码:

function loadXMLDoc()
{
var xmlhttp;
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("1").innerHTML=xmlhttp.responseText;
        }
  }
xmlhttp.open("GET","feedchck.php",true);
xmlhttp.send();
}  

操作按钮:

<button type="button" onclick="loadXMLDoc();">Request</button>
<div id="1">asdf</div>

我已经到了这一步,点击时php文件能够完美地加载。但由于处理需要时间,所以会显示空白区域。那么,在处理期间是否可以显示加载图像或文本,并在完成后隐藏图像并显示文件内容呢?
感谢您的帮助 :}
干杯

1个回答

9
<button type="button" onclick="loadXMLDoc();">Request</button>
<!--An empty tag - this be the loading image-->
<span id="loading"></span>
<div id="1">asdf</div>

<script>
function loadXMLDoc() {
    var xmlhttp;
    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("loading").innerHTML = ''; // Hide the image after the response from the server
            document.getElementById("1").innerHTML = xmlhttp.responseText;
        }
    }
    document.getElementById("loading").innerHTML = '<img src="../loading.gif" />'; // Set here the image before sending request
    xmlhttp.open("GET", "feedchck.php", true);
    xmlhttp.send();
}
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接