我对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();它可以工作并且返回(response.login)//console.log 1),但是如果我使用数据库连接,它就不能。为什么?
发布于 2020-04-17 14:04:40
在Ajax调用中声明dataType。就像-
dataType: 'json'或者将字符串解析为有效的JSON。喜欢
JSON.parse(response);第二件事,通常应该在服务器端对JSON进行编码。请看-
$json = json_encode(array("login" =>"1", "status_"=>1, "user" => 1));发布于 2020-04-17 14:55:55
我让dbconnect.php中的require config.php和脚本正常工作,但这可能是某种异常。
https://stackoverflow.com/questions/61264833
复制相似问题