2011-11-04 152 views
6

我想通過jQuery Mobile網站上的ajax提交一個簡單的登錄表單,但我遇到了麻煩。jQuery Mobile中的AJAX表單提交

看來,當我提交表單(通過POST),表單參數被添加到URL。不僅如此,它們還會清除表單提交之前我所處的錨定頁面。

例如,我頁localhost:8080/myapp/#sign_up

然後我提交表單造成網址變爲:localhost:8080/myapp/[email protected]&pass=pass

所以,如果我打驗證錯誤,然後點擊「返回」按鈕,我不t返回到#sign_up頁面。

任何想法?

回答

15

如果處理表單提交與定製submit事件處理程序,您可以在同一頁面上處理驗證:

//bind an event handler to the submit event for your login form 
$(document).on('submit', '#form_id', function (e) { 

    //cache the form element for use in this function 
    var $this = $(this); 

    //prevent the default submission of the form 
    e.preventDefault(); 

    //run an AJAX post request to your server-side script, $this.serialize() is the data from your form being added to the request 
    $.post($this.attr('action'), $this.serialize(), function (responseData) { 

     //in here you can analyze the output from your server-side script (responseData) and validate the user's login without leaving the page 
    }); 
}); 

從運行表單自身的AJAX sumbission停止jQuery Mobile的把這個表單標籤:

<form data-ajax="false" action="..."> 
+2

任何反饋的反對票將不勝感激。我只是想知道我在做什麼錯:) – Jasper

+0

所以我;-)唯一可能的是,'生活'現在已被棄用,你應該使用'開'。也許甚至'開/關'的順序,以防止重複的事件:http://stackoverflow.com/questions/9067259/ –

0

如果你想提交表單,而不是使用AJAX(這是默認的),你必須添加「數據的Ajax =‘假’」你的格式字符串:

<form data-ajax="false" action="test.php" method="POST"> 
+0

這是上面的答案的一部分,介意如果我問你爲什麼重新張貼它? – Jasper

3

以上Jaspers解決方案爲我工作!我唯一需要調整的就是用.submit替換.live(.live現在已被棄用)。所以現在它是這樣的:

$('#form_id').submit(function (e) { 

    //cache the form element for use in this function 
    var $this = $(this); 

    //prevent the default submission of the form 
    e.preventDefault(); 

    //run an AJAX post request to your server-side script, $this.serialize() is the data from your form being added to the request 
    $.post($this.attr('action'), $this.serialize(), function (responseData) { 

     //in here you can analyze the output from your server-side script (responseData) and validate the user's login without leaving the page 
    }); 
}); 
+0

關於這一點的注意事項,如果表單作爲外部頁面被拉入DOM,那麼必須在發生這種情況之後運行該表單。這就是爲什麼我會建議使用委託事件處理程序,所以即使在初始頁面加載後將表單添加到DOM,事件處理程序也會捕獲該事件。 – Jasper