我有一个反馈表。
<form id="contact_form" action="https://url.com/form/configs/form.php" method="POST">
<div class="form-first">
<input type="text" name="name" value="">
<input type="text" name="email" value="">
</div>
<input type="subject" name="subject" value="">
<textarea name="message" rows="8" cols="80"></textarea>
<input type="submit" name="submit" value="Submit">
</form>
XMLHttpRequest:
const form = document.getElementById('contact_form');
form.addEventListener('submit', function(e) {
e.preventDefault();
const xhr = new XMLHttpRequest();
const action = document.getElementById('contact_form').getAttribute('action');
xhr.open('POST', action, true);
let data = new FormData(form);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onload = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xhr.responseText);
};
};
xhr.send(data);
});
form.php(脚本没有准备好,我只是添加了这些行来测试功能):
<?php
$object = file_get_contents('php://input');
$request = json_decode($object);
echo $request;
?>
但没有什么对我有用。我收到一个错误:
POST https://url.com/form/configs/form.php net::ERR_HTTP2_PROTOCOL_ERROR
错误显示在 ajax 请求的倒数第二行 (xhr.send (data);
)。