jQuery Mobile的避免changePage()的Ajax表单提交表单、Mobile、jQuery、Ajax

2023-09-10 17:37:58 作者:轻声叹

我有一个的形式,我想提交将在 AJAX 的方式,但我不想改变页面的URL。

I have a post form, I want the submit to be done in an AJAX way but I don't want the page URL to change.

例如:

<form action="/countries/change_country" data-ajax="true" method="post">
  <select name="country_code">
    <option value="FR" selected="selected">France</option>
    <option value="DE">Germany</option>
  </select>
  <input type="submit" value="change country" />
</form>

当我点击更改国家按钮的形式是通过AJAX发送什么是好的,但在网页的URL更改为 /国家/ change_country 什么是不是很好,因为这个URL不会在我的服务器存在,这是非常的挑剔的使用HTTP动词。

When I click in the change country button the form is sent through AJAX what is nice but the page URL is changed to /countries/change_country what is not nice because this URL doesn't exist in my server which is very picky with HTTP verbs.

我知道这是可能更改此默认行为,为整个应用程序,但我想停用 changePage()仅适用于这种形式。

I know it is possible to change this default behavior for the whole application but I would like to deactivate the changePage() only for this form.

推荐答案

通过提交表单的使用Javascript / jQuery的代替。

第一的停用默认提交-行为

$('#form').on('submit', function (e) {
   if (e.preventDefault) e.preventDefault();
   return false;
});

二的序列化使用jQuery的表单数据

Second: Serialize the form data with jQuery

var serializedFormData = $('#form').serialize();

第三的:发表表单与 $阿贾克斯();

$.ajax({
   url: '/countries/change_country',
   type: 'POST',
   data: serializedFormData
});