我想使用ajax xmlhttprequest将相同ID的firstname,lastname,email和密码插入到数据库中,然后使用getElementById.value获取所有值,我不知道出了什么问题
function loadDoc() {
var firstname, lastname, email, password;
firstname = document.getElementById("firstname").value;
lastname = document.getElementById("lastname").value;
email = document.getElementById("email").value;
password = document.getElementById("password").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("hero").innerHTML = this.responseText;
}
};
xhttp.open("POST", "action.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("firstname=" + firstname "&lastname=" + lastname "&email=" + email "&password=" + password);
}

<form>
firstname:<input type="text" id="firstname" name="firstname"><br>
Lastname:<input type="text" id="lastname" name="lastname"><br>
Email:<input id="email" type="email" name="email"><br>
Password:<input id="password" type="password" name="password"><br>
<input onclickt="loadDoc()" type="button" name="submit" value="Submit">
</form>
<div id="hero"></div>
&#13;
这是php在$ _POST [&#34;&#34;]
中分配所有内容 $firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$email = $_POST["email"];
$password = $_POST["password"];
if(empty($firstname) || empty($lastname) || empty($email) || empty($password)){
echo '<h2>Empty Firstname</h2>';
header("Location index.php");
} else {
$stmt = mysqli_stmt_init($connection);
$query = "INSERT INTO user (firstname, lastname, email, password) VALUES (?, ?, ?, ?)";
mysqli_stmt_prepare($stmt, $query);
mysqli_stmt_bind_param($stmt, "ssss", $firstname, $lastname, $email, $password);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($connection);
答案 0 :(得分:1)
中存在语法错误
xhttp.send("firstname=" + firstname "&lastname=" + lastname "&email=" + email "&password=" + password);
将其更改为
xhttp.send("firstname=" + firstname + "&lastname=" + lastname + "&email=" + email + "&password=" + password);
你错过了“+”。
另外,另一个在“onclickt”
<input onclickt="loadDoc()" type="button" name="submit" value="Submit">
应该是
<input onclick="loadDoc()" type="button" name="submit" value="Submit">