与
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
,以几个字节为单位。