與
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 ,以幾個位元組為單位。