jQuery Mobile 中的 AJAX 表单提交 [英] AJAX Form Submission in jQuery Mobile
问题描述
我正在尝试通过 ajax 在 jQuery Mobile 网站上提交一个简单的登录表单,但遇到了问题.
I'm trying to submit a simple login form via ajax on a jQuery Mobile site but I'm having trouble.
似乎当我提交表单(通过 POST)时,表单参数被添加到 url 中.不仅如此,他们还删除了我在提交表单之前所在的锚定页面.
It seems that when I submit the form (via POST), the form parameters are getting added to the url. Not only that, they erase the anchored page I was at before form submission.
例如,我在页面 localhost:8080/myapp/#sign_up
然后我提交表单,导致 URL 变为:localhost:8080/myapp/?email=a@a.com&pass=pass
Then I submit the form causing the url to become: localhost:8080/myapp/?email=a@a.com&pass=pass
因此,如果我遇到验证错误并单击返回"按钮,则不会返回到 #sign_up
页面.
So if I hit validation errors and click a 'back' button, I don't get returned back to the #sign_up
page.
有什么想法吗?
推荐答案
如果您使用自定义 submit
事件处理程序处理表单提交,您可以在同一页面上处理验证:
If you handle form submission with a custom submit
event handler you can handle validation on the same page:
//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 sumbission,请将其放在表单标签上:
To stop jQuery Mobile from running its own AJAX sumbission of your form put this on your form tag:
<form data-ajax="false" action="...">
这篇关于jQuery Mobile 中的 AJAX 表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!