以下代码返回对ajax的错误部分的响应。我做错了什么?
JS代码:
var firstName = $('input[name=first]').val(),
lastName = $('input[name=last]').val();
$.ajax({
url: "add-user.php",
type: "POST",
data: {
first: firstName,
last: lastName
},
success: function (response) {
console.log(response);
},
error: function (err) {
console.log(err)
}
});
PHP代码:
<?php
$dbConnect = mysqli_connect("localhost", "root", "password", "db");
$stmt = $dbConnect->prepare("INSERT INTO pokemon (firstName, lastName) VALUES (?, ?)");
$stmt->bind_param('ss', $firstName, $lastName);
$firstName = $_POST['first'];
$lastName = $_POST['last'];
$stmt->execute();
?>
HTML:
<form action="" method="POST" name="addUser" class="user-input">
<label>First Name: <input type="text" name="first"></label> <br>
<label>Last Name: <input type="text" name="last"></label> <br>
<input type="submit" value="Submit" class="user-submit">
</form>
提交数据库正常,但响应返回错误:
Object {readyState: 0, status: 0, statusText: "error"}
答案 0 :(得分:0)
你必须首先初始化变量。
<?php
$firstName = $_POST['first'];
$lastName = $_POST['last'];
$dbConnect = mysqli_connect("localhost", "root", "password", "db");
$stmt = $dbConnect->prepare("INSERT INTO pokemon (firstName, lastName) VALUES (?, ?)");
$stmt->bind_param('ss', $firstName, $lastName);
$stmt->execute();
?>
像这样制作ajax
$("#userForm").submit(function(e){
url: "add-user.php",
type: "POST",
data: $(this).serialize(),
success:function(data){console.log(data);}
});
HTML
<form action="" method="POST" name="addUser" id="userForm" class="user-input">
<label>First Name: <input type="text" name="first"></label> <br>
<label>Last Name: <input type="text" name="last"></label> <br>
<input type="submit" value="Submit" class="user-submit">
</form>
答案 1 :(得分:0)
你假设php明智地理解JSON - 它没有。
您需要转换ajax以发送“url-encoded”数据,或者让php解析正文(包含JSON字符串)。