要实现表单输入和文本区输入的AJAX提交到MySQL数据库,你可以按照以下步骤进行操作:
function submitForm() {
var xhr = new XMLHttpRequest();
var url = "submit.php"; // 替换为你的服务器端处理脚本的URL
// 获取表单数据
var formData = new FormData(document.getElementById("myForm"));
// 发送POST请求
xhr.open("POST", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// 请求成功,执行你的操作
console.log(xhr.responseText);
}
};
xhr.send(formData);
}
connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 获取AJAX请求中的数据
$name = $_POST["name"];
$comment = $_POST["comment"];
// 插入数据到MySQL数据库
$sql = "INSERT INTO comments (name, comment) VALUES ('$name', '$comment')";
if ($conn->query($sql) === TRUE) {
echo "数据插入成功";
} else {
echo "数据插入失败: " . $conn->error;
}
$conn->close();
?>
请确保将上述PHP代码保存为submit.php文件,并将"your_username"、"your_password"和"your_database"替换为你的数据库凭据和数据库名称。
在这个示例中,当用户点击提交按钮时,JavaScript函数submitForm()将使用AJAX将表单数据发送到submit.php脚本。服务器端脚本将接收到的数据插入到MySQL数据库中,并返回一个响应,该响应将在控制台中打印出来。
请注意,这只是一个简单的示例,你可能需要根据自己的需求进行修改和改进。确保在实际使用中进行适当的安全性检查和数据验证。
上一篇:表单输入要求字段不能为空
下一篇:表单输入值不能从脚本中更新。