jQuery Mobile中的AJAX表单提交

时间:2011-11-04 16:40:48

标签: jquery-mobile jquery-validate ajaxform

我正在尝试通过jQuery Mobile网站上的ajax提交一个简单的登录表单,但我遇到了麻烦。

似乎当我提交表单(通过POST)时,表单参数会被添加到url中。不仅如此,他们还删除了表单提交前我所处的锚定页面。

例如,我在页面localhost:8080/myapp/#sign_up

然后我提交表单,导致网址变为:localhost:8080/myapp/?email=a@a.com&pass=pass

因此,如果我点击验证错误并点击“返回”按钮,我就不会返回#sign_up页面。

有什么想法吗?

3 个答案:

答案 0 :(得分: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
    });
});

要阻止jQuery Mobile运行自己的表单的AJAX汇总,请将其放在表单标记上:

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

答案 1 :(得分: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
    });
});

答案 2 :(得分:0)

如果您想提交表单而不使用ajax(默认设置),则必须添加&#39; data-ajax =&#34; false&#34;&#39;到您的表单字符串:

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