dd

Ajax 表单提交


Framework7 可以通过ajax自动提交

有两种自动提交方式:

  • 当用户提交了表单 (点击了提交按钮) 或者当通过代码触发了 "submit" 事件
  • 当用户更改了表单的内容,或者当通过代码触发了 "change" 事件

submit时提交表单数据

只需要添加 "ajax-submit" class 在form上,当submit时就会自动通过ajax发送表单数据

<form action="send-here.html" method="GET" class="ajax-submit">
    ...
</form>

 

当我们提交这个表单时,会自动使用Ajax发送表单的数据,这个过程有一下规则:

  • 表单的数据会发送到 "action" 属性 指定的url

  • request method 通过表单的 "method" 属性来指定

  • Content-Type 通过表单的 enctype 属性来指定,默认值是 application/x-www-form-urlencoded

当表单数据改变时提交数据

很多时候我们在表单中没有使用 "submit" 按钮,这种情况下我们需要当表单有任何数据改变的时候就提交数据。这种情况我们需要使用 "ajax-submit-onchange" class:

     <form action="send-here.html" method="GET" class="ajax-submit-onchange">
    ...
</form>

 

And when user will change any form filed, form data automatically will be sended using Ajax with the same rules as in previous case.

Ajax submit event

Sometimes we need to get actual XHR repsonse from the file/url where we send form data with Ajax. We can use special event for that:

EventTargetDescription
submittedForm Element<form class="ajax-submit">Event will be triggered after successful Ajax request
beforeSubmitForm Element<form class="ajax-submit">Event will be triggered right before Ajax request
submitErrorForm Element<form class="ajax-submit">Event will be triggered on Ajax request error
<form action="send-here.html" method="GET" class="ajax-submit-onchange">
...
</form>

 

当用户改变了任何表单输入数据时,表单的数据就会自动通过ajax发送。

Ajax 提交事件

有时候我们需要用到Ajax的 XHR 对象,可以通过特定的事件来获取:

事件目标描述
submittedForm Element<form class="ajax-submit">Ajax 提交成功后会触发此事件
var myApp = new Framework7();
var $$ = Framework7.$;
$$('form.ajax-submit').on('submitted', function (e) {
  var xhr = e.detail.xhr; // actual XHR object
  var data = e.detail.data; // Ajax repsonse from action file
  // do something with response data
});