js 以 json 格式 post form data
用 js 发起请求,以避免页面跳转
<form action="/hello" method="POST" onsubmit="submitFormData(event)">
<input type="text" name="name" required placeholder="username"><br>
<input type="password" name="password" required placeholder="password"><br>
<input type="submit" value="submit">
</form>
<form action="/world" method="POST" onsubmit="submitJson(event)">
<input type="text" name="name" required placeholder="username"><br>
<input type="password" name="password" required placeholder="password"><br>
<input type="submit" value="submit">
</form>
<script type="text/javascript">
function submitFormData(event) {
event.preventDefault()
const form = event.target
fetch(form.action, {
method: form.method,
body: new FormData(form),
})
.then(async res => {
if (res.ok) {
return await res.json()
}
return await Promise.reject(await res.text())
})
.then(res => console.log(res))
.catch(error => console.error(error))
}
function submitJson(event) {
event.preventDefault()
const form = event.target
const formData = new FormData(form)
const formDataObject = Object.fromEntries(formData.entries())
const formDataJsonString = JSON.stringify(formDataObject)
fetch(form.action, {
method: form.method,
headers: {
'Content-Type': 'application/json'
},
body: formDataJsonString // body data type must match "Content-Type" header
})
.then(async res => {
if (res.ok) {
return await res.json()
}
return await Promise.reject(await res.text())
})
.then(res => console.log(res))
.catch(error => console.error(error))
}
</script>
+V why_null 请备注:from博客园