簡體   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