我正在尝试使用 JS 中的 AJAX 发送我的表单输入。
实际代码如下所示:
const form = document.querySelector('#login');
form.addEventListener('submit', function (event) {
event.preventDefault();
fetch('page.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(new FormData(this))
})
.then(response => response.json())
.then(result => {
console.log('Success:', result);
})
.catch(error => {
console.error('Error:', error);
});
});
这里的问题是在我的 PHP 页面中,
print_r($_POST);
给我返回了一些空白。
如果需要,请填写 HTML 表单:
<form id="login">
<div class="form-group mb-3">
<input type="email" class="form-control" name="USR_Email" placeholder="Email Address">
</div>
<div class="form-group mb-3">
<input type="password" class="form-control" name="USR_Password" placeholder="Password">
</div>
<div class="d-grid mt-4">
<button type="submit" class="btn btn-primary">Login</button>
<input type="hidden" name="action" value="login">
</div>
</form>
我错过了什么吗?
谢谢。
问题的根源在于
JSON.stringify(new FormData(this))
不输出任何内容。
有多种方法可以正确地将 FormData
序列化为 JSON,但是您还需要更改 PHP 代码以正确地接收 POSTed JSON 数据。 一个更简单的解决方案是直接从等式中取出 JSON,并直接提供 FormData 对象,
fetch()
会自动为您进行 URL 编码,然后 PHP 会自动为您解析为
$_POST
数组。就写吧
fetch('page.php', {
method: 'POST',
body: new FormData(this)
})