在ajax获取文件内容时显示加载图像

时间:2012-05-18 04:43:35

标签: ajax

我是ajax的新手并且读了一些tuts来创建一个有多个按钮的lil脚本,并且点击每个脚本将在特定的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 个答案:

答案 0 :(得分:3)

<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>
相关问题