jquery - 使用mysql和ajax时访问json字符串中的变量的问题
问题描述
我对 jquery 有一些问题。为什么访问 json 字符串中的变量会出现问题?
$(function() {
var jqxhr = $.ajax({
type: "POST",
url: "test.php",
async: false,
cache: false,
timeout: 10000,
data: {
test: "test"
},
success: function(response) {
console.log(response); // {"login":"1","status_":0,"user":1}
console.log(response.login); //undefined
test = JSON.parse(response); // Uncaught SyntaxError: Unexpected token in JSON at position 2
console.log(test.login); //not work
},
complete: function(response) {
}
});
})();
test.php
require("config.php");
require("dbconnect.php");
$sth = $dbh->prepare('SELECT * FROM users WHERE email=?');
$sth->bindParam(1, $_POST["login"], PDO::PARAM_STR);
$sth->execute();
$user = $sth->fetch();
if(@$user['email']==$_POST["test"]) {
$json = json_encode(array("login" =>"1","status_"=>0, "user" => 1), JSON_UNESCAPED_UNICODE);
}
else {
$json = json_encode(array("login" =>"1", "status_"=>1, "user" => 1), JSON_UNESCAPED_UNICODE);
}
echo $json;
这是一个小的 php 脚本,它通过简单的条件返回单个 JSON 字符串。
如果我不使用下面的代码:
require("config.php");
require("dbconnect.php");
$sth = $dbh->prepare('SELECT * FROM users WHERE email=?');
$sth->bindParam(1, $_POST["test"], PDO::PARAM_STR);
$sth->execute();
$user = $sth->fetch();
它可以工作并且 console.log(response.login)//return 1),但是如果我使用数据库连接,它不会。为什么?
解决方案
dataType
在您的 Ajax 调用中声明。喜欢 -
dataType: 'json'
或者将您的字符串解析为有效的 JSON。喜欢
JSON.parse(response);
您通常应该在服务器端对 JSON 进行编码的第二件事。看 -
$json = json_encode(array("login" =>"1", "status_"=>1, "user" => 1));
推荐阅读
- sql - Microsoft Query 中 DISTINCT 的总和
- sql - SQL查询仅根据一个“分组依据”下的两个分隔列获取与条件匹配的行
- angular - 无法在 Jest 中模拟 Renderer2
- c# - 如何使点击以透明形式穿过形状
- python - 列表字典到嵌套字典
- python - 熊猫:使用正则表达式更新列
- angular - 运行 npm install -g @angular/cli 时出现权限错误
- git - 如何使用 Git 在 Visual Studio Code 中的分支之间切换?
- javascript - 发送查询后加载数组时出现错误上下文
- ansible - 使用 ansible 运行服务时使用系统范围的环境变量