簡體   English   中英

如何使用 Fetch API 從表單中檢索和發送數據?

[英]How to use Fetch API to retrieve and send data from form?

我有 html 形式:

<form action="file.php" method="post">
    <input name="formName" type="text" />
    <input name="formEmail" type="email" />
    <input name="formSubmit" type="submit" value="Submit Me!" />
</form>

那么如何使用 Fetch API 獲取這些值並使用 ajax 將它們發送到 file.php 文件呢?

使用提取API

 function submitForm(e, form){ e.preventDefault(); fetch('file.php', { method: 'post', body: JSON.stringify({name: form.formName.value, email: form.formEmail.value}) }).then(function(response) { return response.json(); }).then(function(data) { //Success code goes here alert('form submited') }).catch(function(err) { //Failure alert('Error') }); } 
 <form action="file.php" method="post" onsubmit="submitForm(event, this)"> <input name="formName" type="text" /> <input name="formEmail" type="email" /> <input name="formSubmit" type="submit" value="Submit Me!" /> </form> 

我建議使用FormData 如果編碼類型設置為“multipart/form-data”,它使用的格式與表單使用的格式相同。 有關它的更多詳細信息。

    const submitForm = () => {
        const formEl = document.getElementById('formId');
        const payload = new FormData(formEl);

        fetch('file.php', {
            method: 'POST',
            body: payload,
        })
        .then(Result => Result.json())
        .then(data => {
            console.log(data);
            // your code comes here
        })
        .catch(errorMsg => {
            console.log(errorMsg);
        });

    };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM