1

クイックノート。私はjQueryを使用していないので、提案しないでください。

onclick = "ajaxfunction();"のあるボタンを押したとき 「AJAX呼び出し中にエラーが発生しました。もう一度やり直してください」というアラートが表示されたら、成功というアラートが2回表示されます: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>
4

1 に答える 1

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;
       }
    }

これがお役に立てば幸いです。

于 2012-12-28T16:49:08.957 に答える