首页 > 解决方案 > 使用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),但是如果我使用数据库连接,它不会。为什么?

标签: jquerymysqljsonajax

解决方案


dataType在您的 Ajax 调用中声明。喜欢 -

dataType: 'json'

或者将您的字符串解析为有效的 JSON。喜欢

JSON.parse(response);

您通常应该在服务器端对 JSON 进行编码的第二件事。看 -

$json = json_encode(array("login" =>"1", "status_"=>1, "user" => 1));

推荐阅读