2017-07-28 162 views
-2

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

<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> 

因此,如何使用才能獲取API來獲取這些值,並送他們使用AJAX file.php文件?

+0

看看這個頁面在這裏:https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-以獲取數據 –

+0

@FotisGrigorakis謝謝,但我需要一個確切的例子與形式和PHP。 – tohhy

+0

你可以按照我寫的網站中的步驟進行操作。 ;) –

回答

0

使用Fetch 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>

+0

它說「錯誤」。 – tohhy

+0

''file.php'檢查php路徑是否正確? –

+0

謝謝你的回答!路徑不正確。 – tohhy

相關問題