与
form.submit()类似,但采用 ajax 方式。轻量级、现代、承诺、使用fetch
您可以使用pushForm(form)通过fetch发送表单,而不是像form.submit()那样导致页面加载。它使用现代 API 自动读取所有字段,并完全按照form属性所描述的方式执行请求。
npm install push-form
// This module is only offered as a ES Module
import pushForm from 'push-form' ; 给定一个常规的表单元素:
< form action =" submissions.php " type =" post " >
First name < input name =" firstname " required /> < br />
Last name < input name =" lastname " required /> < br />
Passport < input name =" passport " type =" file " required />
< button > Submit </ button >
</ form >您可以通过fetch发布它:
import pushForm from 'push-form' ;
const form = document . querySelector ( 'form' ) ;
form . addEventListener ( 'submit' , async event => {
event . preventDefault ( ) ;
const response = await pushForm ( ) ;
if ( response . ok ) {
alert ( 'Thanks for your submission!' ) ;
}
} ) ;或者使用ajaxifyForm让它自动处理用户提交:
import { ajaxifyForm } from 'push-form' ;
const form = document . querySelector ( 'form' ) ;
ajaxifyForm ( form , {
onSuccess : ( ) => { /* ✅ */ } ,
onError : ( ) => { /* */ } ,
} ) ; 返回一个Promise ,该 Promise 会像fetch一样通过Response进行解析。
类型: HTMLFormElement
要提交的表格。其action和method属性将用于创建 HTTP 请求。
类型: object
示例: {headers: {Accept: 'application/json'}}
这与fetch的第二个参数匹配,但是body和method将被form元素在其属性中指定的内容覆盖。
停止表单的submit事件并使用pushForm代替。这会返回一个function ,您可以调用该函数来删除submit处理程序。
和pushForm中的一样
类型: object
可选的提交/错误处理程序和fetch的配置。
类型: function
示例: (fetchResponse) => {alert('The form was submitted!')}
当fetch发出请求并且服务器返回成功响应( response.ok )时,它将被调用
类型: function
示例: (error) => {alert('Something happened:' + error.message)}
当fetch请求失败或服务器返回错误响应时( response.ok === false ),它将被调用
与pushForm中的相同。
querySelector /输出数组的All包装器。DocumentFragment或一个Element ,以几个字节为单位。