2011-11-04 157 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