2011-10-20 116 views
2

在使用ajax进行一些编码时,我发现一个问题。以下是我的代码片段。停止表单请求,直到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请求之前应该等待表单提交。

我发现此链接与我的相似。 Sending an Ajax request before form submit

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

回答

0

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

更新:你可以这样写。你需要做的是用提交按钮的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> 
+0

请问你能告诉我该怎么做? – bunkdeath

+0

立即查看我的编辑。 – Kangkan

+0

我得到了你想说的话。但我的问题是不同的。由于按钮位于表单标签内,因此单击按钮本身会提交表单。所以,当我点击按钮时,我猜Ajax调用以及表单提交一起工作,并且在提交Ajax调用成功表单之前。 – bunkdeath