【问题标题】:Button calls ajax function multiple按钮多次调用ajax函数
【发布时间】:2012-12-13 21:09:40
【问题描述】:

快速笔记。我没有使用 jQuery,所以不建议使用它。

按下具有 onclick="ajaxfunction();" 的按钮时我收到警告说“AJAX 调用期间出错。请重试”,然后我收到警告说成功,两次:S ... 为什么会发生这种情况?

我不明白为什么会这样,因为它调用了错误,然后转到 if 语句的另一部分......

提前致谢!

<script>

    function getXMLObject()  //XML OBJECT
    {
       var xmlHttp = false;
       try {
         xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")  // For Old Microsoft Browsers
       }
       catch (e) {
         try {
           xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")  // For Microsoft IE 6.0+
         }
         catch (e2) {
           xmlHttp = false   // No Browser accepts the XMLHTTP Object then false
         }
       }
       if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
         xmlHttp = new XMLHttpRequest();        //For Mozilla, Opera Browsers
       }
       return xmlHttp;  // Mandatory Statement returning the ajax object created
    }

    var xmlhttp = new getXMLObject();   //xmlhttp holds the ajax object
    var url="insertProduct.php";

    function ajaxFunction() {
      var getdate = new Date();  //Used to prevent caching during ajax call
      if(xmlhttp) {
        var name = document.getElementById("name");
        var code = document.getElementById("code");
        xmlhttp.open("POST",url,true); //calling insertProduct.php using POST method
        xmlhttp.onreadystatechange  = handleServerResponse;
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp.send("name=" + encodeURIComponent(name.value) + "&code=" + encodeURIComponent(code.value)); //Posting to PHP File

      }
    }

    function handleServerResponse() {
       if (xmlhttp.readyState == 4 || xmlhttp.readyState=="complete") {
           alert("Success");
           document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element 
       }
       else {
            alert("Error during AJAX call. Please try again " + xmlhttp.status);
       }
    }
</script>

【问题讨论】:

  • 我没有使用 jQuery,所以不建议这样做。 ...为什么不呢?
  • 这个项目的限制。
  • @mombassa 那么我强烈建议您划定您的项目..
  • 这是给大学的。试着帮忙怎么样?而不是仅仅抨击它;这些是要求,我不是在这里重新讨论它们,而是解决手头的问题。如果您不能提供帮助,请不要发表评论。
  • @Mombassa:完成工作的最有效方法是不要重新发明轮子。

标签: php html ajax forms xmlhttprequest


【解决方案1】:

完成任务后可以拨打return;

喜欢下面。

function handleServerResponse() {
       if (xmlhttp.readyState == 4 || xmlhttp.readyState=="complete") {
           alert("Success");
           document.getElementById("message").innerHTML=xmlhttp.responseText; 
           return; 
       }
       else {
            alert("Error during AJAX call. Please try again " + xmlhttp.status);
            return;
       }
    }

希望对你有帮助。

【讨论】:

  • 你会得到 + 的帮助:D
  • 是的,问题是状态码之类的,但你引起了我的注意。
猜你喜欢
  • 2019-10-04
  • 2017-04-21
  • 2013-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-04
相关资源
最近更新 更多