【发布时间】:2017-10-01 15:09:12
【问题描述】:
我正在尝试通过 ajax 以 json 格式发送身份验证响应。 在 chrome devtools 中,我得到文件 register.ajax.php 的响应 在“网络”上,但从来没有在 javascript 文件中被接受。
在 user.class.php 中,我检查用户 ID/用户名或电子邮件是否已经存在,如果存在,它将发送状态为“错误”或“成功”;
user.class.php
public function register_client($uid, $email, $pwd)
{
$this->db = DB::getInstance();
$stmt = $this->db->prepare("SELECT * FROM user_accounts WHERE uid = :uid OR email = :email");
$stmt->bindParam(":uid", $uid);
$stmt->bindParam(":email", $email);
$stmt->execute();
$query = $stmt->fetch(PDO::FETCH_ASSOC);
$resultado_uid = $query['uid'];
$resultado_email = $query['email'];
if ($resultado_uid || $resultado_email)
{
$response_array['status'] = 'error';
echo json_encode($response_array);
}
else
{
$response_array['status'] = 'success';
echo json_encode($response_array);
$basic_password = $pwd;
$hashed_password = password_hash($basic_password, PASSWORD_BCRYPT);
$stmt = $this->db->prepare("INSERT INTO user_accounts(uid, email, pwd) VALUES (:uid, :email, :pwd)");
$stmt->bindParam(":uid", $uid);
$stmt->bindParam(":email", $email);
$stmt->bindParam(":pwd", $hashed_password);
$stmt->execute();
}
}
通过 ajax 文件,只要设置了操作 'register_client',我只需激活 register_client 公共函数(似乎也很好);
register.ajax.php
<?php
require_once "../header.php";
if(isset($_POST['action'])) $action = $_POST['action'];
if($action == 'register_client'){
$cliente->register_client($_POST['uid'], $_POST['email'], $_POST['pwd']);
}
注册表格应该没问题(只是一个简单的表格,动作也匹配)
register.php
<?php
require_once "header.php";
require_once "nav.php"
?>
<form action="" method="POST">
<input type="text" name="uid" id="uid" placeholder="username"><br>
<input type="email" name ="email" id="email" placeholder="email"><br>
<input type="password" name="pwd" id="pwd" placeholder="password"><br>
<button name="register_client" id="register_client" type="submit">Register</button>
</form>
<?php
include "footer.php";
?>
这似乎是问题的根源,成功函数没有检索任何数据。尝试在其中执行 console.log(data) 以查看它给了我什么,但到目前为止什么都没有。
$(document).ready(function() {
$("#register_client").on("click", function() {
var uid = $("#uid").val();
var email = $("#email").val();
var pwd = $("#pwd").val();
$.ajax({
type: 'post',
url: 'ajax/register.ajax.php',
dataType: 'json',
data: {
'uid': uid,
'email': email,
'pwd': pwd,
'action': 'register_client',
},
success: function(data) {
console.log(data);
},
error: function() {
console.log("it failed");
}
});
return false;
});
});
【问题讨论】:
-
您是否查看过浏览器控制台的 NET 选项卡以查看原始响应?您可能会在那里找到一些线索,例如某些 PHP 错误会破坏您的响应。如果是这种情况,请修复错误。此外,您可能会考虑使用输出缓冲来捕获错误,这样您就可以控制错误的处理方式。
-
我得到了整个 ,然后是“NETWORK-> response”devtools 上的成功响应
-
一个json响应只能是json。您必须删除所有其他输出。
标签: javascript php jquery json ajax