使用xmlhttprequest插入数据库
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用xmlhttprequest插入数据库相关的知识,希望对你有一定的参考价值。
我想使用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>
这里是PHP分配$ _POST [“”]中的所有内容
$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);
答案
你有一个语法错误
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">
以上是关于使用xmlhttprequest插入数据库的主要内容,如果未能解决你的问题,请参考以下文章
代码片段使用复杂的 JavaScript 在 UIWebView 中插入 HTML?
c_cpp 这个简单的代码片段显示了如何使用有符号整数在C中完成插值。 for()循环确定要插入的范围