javascript - 如何显示 div 直到 XHR 请求完成

标签 javascript html ajax

我用 php 创建了一个井字棋游戏。我创建了以下代码来显示网格并将请求发送到 php-

<html>
<head>
<script type="text/javascript">
function showData(str)
{
    if(str==""){
        document.getElementById("showData").innerHTML="";
    }
    if(window.XMLHttpRequest){
        //code for IE7+, Firefox, Chreom, 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("showData").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","tttoe?move="+str,true);
    xmlhttp.send();
}
</script>
</head>
<body>
<center>
<div id="showData">
<table border="1" cellpadding="1" cellspacing="1">
    <tr>
        <td>&nbsp;<input type="button" class="button1" name="move" value="1" onClick="showData(this.value)" />&nbsp;</td>
        <td>&nbsp;<input type="button" class="button1" name="move" value="2" onClick="showData(this.value)" />&nbsp;</td>
        <td>&nbsp;<input type="button" class="button1" name="move" value="3" onClick="showData(this.value)" />&nbsp;</td>
    </tr>
    <tr>
        <td>&nbsp;<input type="button" class="button1" name="move" value="4" onClick="showData(this.value)" />&nbsp;</td>
        <td>&nbsp;<input type="button" class="button1" name="move" value="5" onClick="showData(this.value)" />&nbsp;</td>
        <td>&nbsp;<input type="button" class="button1" name="move" value="6" onClick="showData(this.value)" />&nbsp;</td>
    </tr>
    <tr>
        <td>&nbsp;<input type="button" class="button1" name="move" value="7" onClick="showData(this.value)" />&nbsp;</td>
        <td>&nbsp;<input type="button" class="button1" name="move" value="8" onClick="showData(this.value)" />&nbsp;</td>

        <td>&nbsp;<input type="button" class="button1" name="move" value="9" onClick="showData(this.value)" />&nbsp;</td>
    </tr>
</table>
</div>
</center>
</body>
</html>

有没有办法让我可以显示文本(正在处理......)直到请求完成?

最佳答案

您可以在 html 和 js 中添加带有 id statusdiv:

document.getElementById('status').innerHTML = 'processing';

在函数的开头并且

document.getElementById('status').innerHTML = 'whatever you want';

之后

if(xmlhttp.readyState==4 && xmlhttp.status==200){

关于javascript - 如何显示 div 直到 XHR 请求完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11969011/

相关文章:

javascript - JQuery 中的倒计时问题

javascript - PhoneGap 在应用程序浏览器中按后退键时未关闭

javascript - 加载 gif 不等待 iFrame 加载?

jquery - 为什么 $() 在谷歌工作?

php - AJAX 表单只执行一次(第一次输入)

javascript - AJAX:如何读取 JSON 数据

javascript - MVC Controller 返回 JSON

javascript - 数值数组排序()

javascript - 不知道如何消除 MongoDB 中的重复键错误

html - Google PageSpeed Insights 根据视口(viewport)调整内容大小