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