我目前正在尝试在 XAMPP 上创建一个注册页面。我的系统的摘要是,当用户单击提交按钮时,JS 通过 POST 对 php 文件执行 xmlhttprequest,将用户的数据上传到数据库并创建一个新帐户。然而,经过一些调试后,我们发现 php 文件似乎没有收到 any 的 POST 数据。
我的JS:
form.addEventListener("submit", function (ev) {
ev.preventDefault();
xhr = new XMLHttpRequest();
xhr.timeout = 10000;
xhr.open("POST", "/db/signup.php");
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=---------------------------974767299852498929531610575");
xhr.addEventListener("timeout", function () {
errorMsg("Timed out. Try again later.")
}, false);
xhr.addEventListener("readystatechange",
function () {
if (xhr.readyState == 4) {
if (xhr.status == 200 && xhr.responseText !== null) {
// if (xhr.responseText.startsWith("ERROR: ")) { regular code
// loadingIcon.style.opacity = "0";
// errorMsg(xhr.responseText.slice(6));
// } else {
// location.href = "/?message=Created%20account!";
// }
errorMsg(xhr.responseText); // debugging code
} else {
location.href = "/500.html";
}
}
},
false);
xhr.send(new FormData(form));
}, false);
我的PHP:
try {
$statement = $pdo->prepare("INSERT INTO users (name, email, password, birthday, imgpath) VALUES (:n, :e, :p, :dob, :imgpath)");
$statement->execute(
["n" => $_POST["name"], "e" => $_POST["email"],"p" => password_hash($_POST["password"], PASSWORD_BCRYPT), "dob" => $_POST["dob"], "imgpath" => $path ?? ""]);
} catch (PDOException $e) {
if ($e->errorInfo[1] == 1062) {
$error = "Already an account with email \"" . htmlspecialchars($_POST["email"], ENT_QUOTES | ENT_HTML5) . "\"";
} else {
$error = "An error occured. Try again later.";
}
}
注意:这些只是我整个代码的一部分
我希望您能找到解决我的问题的方法。感谢所有帮助!
删除
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=---------------------------974767299852498929531610575");
来自您的 Javascript 代码。您无需手动设置,XHR 将为您处理并确保其正确完成。