ชอบ
form.submit()
แต่ ajaxed น้ำหนักเบา ทันสมัย มีแนวโน้ม ใช้การดึงfetch
แทนที่จะทำให้เพจโหลดเหมือนที่ form.submit()
ทำ คุณสามารถใช้ pushForm(form)
เพื่อส่งแบบฟอร์มผ่านการ fetch
โดยจะอ่านฟิลด์ทั้งหมดโดยอัตโนมัติโดยใช้ 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
ที่แก้ไขด้วย Response
เหมือนกับ fetch
ประเภท: 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
แบบน้ำหนักเบา / wrapper All
ที่ส่งออกอาร์เรย์DocumentFragment
หรือหนึ่ง Element
ในเวลาไม่กี่ไบต์