2013-01-01 60 views
1

問題是,在登錄頁面上,提交不正確的條目後,ajax請求在按提交後不會再次執行。使用jquery的登錄頁面不會重新提交

我已經通過StackExchange搜尋了我的問題的答案,並查看了其他12個鏈接,如Why won't my jQuery form resubmit?jQuery & AJAX login form。看起來我需要解除綁定提交的變量,但不知道如何做到這一點。

HTML

<div data-role="page" id="login"> 
    <div data-role="header" data-position="inline" data-theme="b">  
    <h1>My login</h1> 
    </div><!-- /header --> 
    <div data-role="content"> 
    <form method="post" id="loginform"> 
     <label for="username">Username:</label> <input type="text" name="username" id="username" value="" /> 
     <label for="passwd">Password:</label> <input type="password" name="passwd" id="passwd" value="" /> 
     <input type="submit" value="Login" /> 
    </form> 
    </div><!-- /content --> 
</div><!-- /login page --> 

的JavaScript

$(document).ready(function() { 
    $("#loginform").on('submit',function(event){ 
    var $form = $(this), 
     serializedData = $form.serialize(); 

    // fire off the request to /form.py 
    $.ajax({ 
     url: "https://mywebsite/cgi-bin/form.py", 
     type: "post", 
     data: serializedData, 

     // callback handler that will be called on success 
     success: function(response, textStatus, jqXHR){ 
     console.log(response); 
     // If login is unsuccessful, log message and return to login screen again 
     if (response == "INVALID_USER\n") { 
      alert("sorry, try again"); 
     } else { 
      // Login successful - do something 
     } 
     }, 

     // callback handler that will be called on error 
     error: function(jqXHR, textStatus, errorThrown){ 
     console.log(
      "The following error occured: "+ 
      textStatus, errorThrown); 
     }, 

     // callback handler that will be called on completion 
     // which means, either on success or error 
     complete: function(){ 
     //----- DO I NEED TO UNBIND SOMETHING HERE? 
     var dummy = 1; 
     } 
    }); // end of ajax call 
}); // end of submit handler 
}); 
+0

你把警報在javascript中進行調試嗎?哪裏有問題? – pkachhia

+0

是的警報是有調試。問題是,如果登錄失敗,我重新提交表單,它不起作用 - 服務器請求永遠不會通過。 –

+0

好的告訴我一件事,就是你的頁面通過cgi顯示嗎?你是否通過任何主板運行你的頁面? – pkachhia

回答

1

你會嘗試事件處理程序結束前添加return false?使用return false可防止事件觸發,並防止用戶在未填寫正確的必填字段的情況下繼續。

$("#loginform").on('submit',function(event){ 

    ... 

    return false; 
}); 

此外服務器返回什麼樣的數據類型?例如,如果服務器返回JSON,那麼您應該在AJAX代碼中添加dataType: 'json'。如果沒有指定,jQuery將嘗試根據響應的MIME類型推斷它。

也許你可以使用firebug找出是否發生錯誤。

+0

沒有運氣 - 之前已經嘗試過,甚至在成功處理程序內。 –

+0

在事件處理程序結束時需要返回false。我也更新了我的答案,可能的錯誤原因。 Thnx –

+0

太棒了!這工作 - 謝謝一噸! –