AJAX 表单提交:使用 JavaScript 和 PHP 处理数据
// 监听表单提交事件
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault(); // 阻止表单默认提交行为
// 创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// 设置请求参数
xhr.open('POST', 'submit.php', true);
// 设置请求头
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// 监听请求状态变化
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
alert('提交成功!');
} else {
alert('提交失败!');
}
}
};
// 发送请求
xhr.send(new FormData(event.target));
});
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// 处理表单数据
echo 'OK'; // 返回响应
?>
原文地址: https://www.cveoy.top/t/topic/gmar 著作权归作者所有。请勿转载和采集!