繁体   English   中英

停止表单请求,直到ajax请求完成

[英]stop form request until ajax request completes

在使用ajax进行一些编码时,我发现了一个问题。 以下是我的代码片段。

<script type="text/javascript">
    function xmlHttp(){
        if(window.XMLHttpRequest){
            xmlhttp = new XMLHttpRequest();
        }
        else{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        return xmlhttp;
    }

    function addData(a, b, c){
        xmlhttp = xmlHttp();
        xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState==4 && xmlhttp.status==200){
                alert("Response : " + xmlhttp.responseText);
            }
        }
        link = "test.php?a="+a+"&b="+b+"&c="+c;
        xmlhttp.open("GET",link,true);
        xmlhttp.send();
    }
</script>
<center>
    <form method="POST" action="?page=search.php">
        <table width="400" border="1">
            <tr>
                <td align="right"><button onclick="return addData(1,2,3);">Add data</button></td>
            </tr>
        </table>
    </form>
</center>

单击按钮后,ajax请求将调用。 在ajax请求完成之前,将进行提交。 等待表单提交直到ajax请求完成之前应该做什么。

我发现此链接与我的相似。 在表单提交之前发送Ajax请求

这样做,我的其他表格不发送(其他输入类型)。 POST数组保持为空。

如果您希望用户在AJAX请求完成之前不提交表单,则只需在发送请求时禁用表单,并在收到响应后启用它即可。 您可能还会显示一个loading ... gif,以告诉用户发生了什么事。

更新:您可以这样写。 您需要做的是用Submit按钮的ID替换SubmitBtnId。

<script type="text/javascript">
    function xmlHttp(){
        if(window.XMLHttpRequest){
            xmlhttp = new XMLHttpRequest();
        }
        else{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        return xmlhttp;
    }

    function addData(a, b, c){
        xmlhttp = xmlHttp();
        xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState==4 && xmlhttp.status==200){
                alert("Response : " + xmlhttp.responseText);
                Document.getElementById('SubmitBtnId').disabled=false;
            }
        }
        link = "test.php?a="+a+"&b="+b+"&c="+c;
        Document.getElementById('SubmitBtnId').disabled=true;
        xmlhttp.open("GET",link,true);
        xmlhttp.send();
    }
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM