我正在使用ajax update
将数据写入数据库,如果成功,它会返回一些文本,但是它不起作用
html
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form>
<input type="text" name="name" value="" placeholder="name..." >
<br>
<input type="text" name="email" value="" placeholder="email..." >
<br>
<button id="form-btn" class="btn btn-default" onclick="update()">click me</button>
</form>
</div>
</div>
<div class="row">
<div class="col-md-12"><span id="result">here</span></div>
</div>
</div>
js
function update() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState = 4 && xmlhttp.status == 200) {
// document.getElementById("result").innerHTML = xmlhttp.responseText;
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST","ajax_form.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var str = $("form").serialize();
xmlhttp.send(str);
}
php
$name = $_POST["name"];
$email = $_POST["email"];
if ($sql_insert = $conn->prepare("INSERT INTO $tablename (name, email) VALUES (?, ?)")) {
# Bind the variables to the parameter as strings
if (!$sql_insert->bind_param("ss", $name, $email)) {
echo "binding parameter fail";
}
# Execute the statement
if (!$sql_insert->execute()) {
echo "insert fail: " . $sql_insert->error . "<br>";
} else {
echo "success";
}
# Close the prepared statement
$sql_insert->close();
}
我期望的结果是:当用户提交表单时,它会通知用户在 <span id='result'></span>
中更新成功,但它只是更新数据而不通知。
最佳答案
由于声誉问题,我无法对您的帖子发表评论。但是你的代码有错误。您错过了一个等号
if (xmlhttp.readyState = 4 && xmlhttp.status == 200)
应该是
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
关于javascript - AJAX回调失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30274655/