2014-01-31 38 views
0

我應該將代碼粘貼第一的jQuery的preventDefault不停止執行

$(document).ready(function(){ 
    $("#submit").click(function(e){          
     $(".error").hide(); 
     var hasError = false; 

     .... .... 

     var captcha = $("#captchacode").val(); 
     if(captcha == '') { 
      $("#captchacode").after('<span class="error">You forgot to enter security image.</span>'); 
      hasError = true; 
     } else { 

      $.post("/checkcaptcha.php", 
       { captchac: captcha}, 
        function(data){ 

         if (data == "Invalid"){ 
          $("#captchacode").after('<span class="error">Invalid security text. Please try again</span>'); 
          hasError = true; 
          e.preventDefault(); 
         } 
        } 
      ); 
     } 


     if(hasError == false) { 
      $(this).hide(); 
      $("#sendEmail li.buttons").append('<img src="images/loading.gif" alt="Loading" id="loading" />'); 

      $.post("/sendemail.php", 
       { emailFrom: emailFromVal, name: name, message: messageVal }, 
        function(data){ 
         $("#sendEmail").slideUp("normal", function() {     

          $("#sendEmail").before('<h1>Success</h1><p>Your email was sent.</p>');           
         }); 
        } 
       ); 
     } 

     return false; 
    });       
}); 

一切工作。電子郵件正在發送。我在輸入無效驗證碼值時收到錯誤消息。在顯示錯誤消息之後,它將在下一步中完成,表單正在提交。我需要你的建議來解決這個問題。

謝謝。

回答

1

jQuery.post()函數是AJAX調用的簡寫。 AJAX調用是異步的,並通過傳遞在請求完成時執行的回調來工作。調用$.post()不會停止代碼的執行,直到請求收到響應,因爲AJAX的整個點是爲了而不是發生。這意味着您的if(hasError == false)行將在您的回調函數的if (data == "Invalid")部分之前執行

如果你想要的東西從AJAX調用,那麼你需要將它移動到回調函數響應後發生

$(document).ready(function() { 
    $("#submit").click(function (e) { 
     $(".error").hide(); 
     var hasError = false, 
      elem = this; 

     ........ 

     var captcha = $("#captchacode").val(); 
     if (captcha == '') { 
      $("#captchacode").after('<span class="error">You forgot to enter security image.</span>'); 
      hasError = true; 
     } else { 

      $.post("/checkcaptcha.php", { 
       captchac: captcha 
      }, 

      function (data) { 

       if (data == "Invalid") { 
        $("#captchacode").after('<span class="error">Invalid security text. Please try again</span>'); 
        hasError = true; 
        e.preventDefault(); 
       } else { 
        $(elem).hide(); 
        $("#sendEmail li.buttons").append('<img src="images/loading.gif" alt="Loading" id="loading" />'); 

        $.post("/sendemail.php", { 
         emailFrom: emailFromVal, 
         name: name, 
         message: messageVal 
        }, 

        function (data) { 
         $("#sendEmail").slideUp("normal", function() { 

          $("#sendEmail").before('<h1>Success</h1><p>Your email was sent.</p>'); 
         }); 
        }); 
       } 
      }); 
     } 
     return false; 
    }); 
});