form.submit()
과 비슷하지만 ajax입니다. 경량, 현대적, 약속, 가져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 : ( ) => { /* */ } ,
} ) ;
fetch
오기와 똑같이 Response
으로 해결되는 Promise
반환합니다.
유형: HTMLFormElement
제출할 양식입니다. 해당 action
및 method
속성은 HTTP 요청을 생성하는 데 사용됩니다.
유형: object
예: {headers: {Accept: 'application/json'}}
이는 fetch
의 두 번째 매개변수와 일치하지만 body
과 method
form
요소가 해당 속성에 지정하는 내용으로 재정의됩니다.
양식의 submit
이벤트를 중지하고 대신 pushForm
사용합니다. 이는 submit
핸들러를 제거하기 위해 호출할 수 있는 function
반환합니다.
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
로 구문 분석합니다.