6

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

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

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

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

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

有任何想法吗?

4

3 回答 3

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="...">
于 2011-11-04T17:06:32.887 回答
3

上面的 Jaspers 解决方案对我有用!我唯一需要调整的是将 .live 替换为 .submit (.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
    });
});
于 2013-08-15T15:31:25.440 回答
0

如果您想提交表单而不使用 ajax(这是默认设置),您必须在表单字符串中添加 'data-ajax="false"':

 <form data-ajax="false" action="test.php" method="POST">
于 2013-05-22T13:35:51.333 回答