【发布时间】:2017-10-20 09:22:50
【问题描述】:
我正在对 php 脚本使用 ajax 请求来注册新用户,它可以工作并将其保存在数据库中,但返回错误而不是成功。
这是我的 ajax 请求:
$.ajax({
type: "POST",
url: "http://localhost/webAPI/register.php",
data: dataString,
crossDomain: true,
cache: false,
success: function (data) {
if (data == 1)
alert("success");
else(data == 0 )
alert("error");
},
error: function (){
alert("An Error Ocurred");
}
});
这是我的 php 脚本:
if($_POST)
{
$user_name = $_POST['username'];
$user_password = $_POST['password'];
$joining_date = date('Y-m-d H:i:s');
//password_hash see : http://www.php.net/manual/en/function.password-hash.php
$password = password_hash( $user_password, PASSWORD_BCRYPT, array('cost' => 11));
//if($count==0){
$stmt = $db_con->prepare("INSERT INTO users(username,password,joiningdate) VALUES(:uname,:pass,:jdate)");
$stmt->bindParam(":uname",$user_name);
$stmt->bindParam(":pass",$user_password);
$stmt->bindParam(":jdate",$joining_date);
if($stmt->execute())
{
echo 1;
}
else
{
echo 0;
}
}
【问题讨论】:
-
您收到什么警报? “错误”还是“发生错误”?
-
在 Ajax 函数中对数据对象进行 json 字符串化
-
发生错误
-
好吧,看我的回答,看
error函数,它一定会告诉你更多关于错误的信息。 -
问题是,它必须在 ajax 请求中包含 datatype: 'json' 。就是这样!