【发布时间】:2019-02-02 12:30:57
【问题描述】:
当我想检查新转换的类型时,我不知道为什么使用 JSON.parse function 格式化为 json 的数据返回为 Array type。
首先我发出 ajax 请求从数据库中获取数据,如下图所示
$.ajax({
url:'processBet.php',
data:'',
success:function(data){
//below I check the return data type
console.log( Object.getPrototypeOf(JSON.parse(data)));
//the return type is array.....why?
console.log((JSON.parse(data)); // to see the data
}
});
显然,在数据库中获取数据的文件会将数据放入数组中。所以在发送之前,我使用一个php函数json_encode将其转换为JSON,如下图所示
$ql = "SELECT * from tempdata" ;
$result=$pdo->query($ql);
$result->setFetchMode(PDO::FETCH_ASSOC);
while($data = $result->fetch()){
$arrays[]=$data;
}
//Now I convert in json before sending
$json =json_encode($arrays);
echo $json; // the return data supposed to be json type
所以我想知道为什么返回类型仍然是数组而不是 JSON,因为当 ajax 请求成功时已经进行了新的转换
【问题讨论】:
-
因为你把它通过
JSON.parse,它把它变成了你json_encode之前的数组。你应该试试console.log( Object.getPrototypeOf(data));,它会给你String。 -
是的,我这样做是为了获取返回数据的类型。我的问题是:它是否正确,因为我必须确定这一点,以免出现错误。谢谢
-
数组不是类型,JSON 也不是。 Object.getPrototypeOf 有效地返回在
[[Prototype]]链上找到的第一个原型的构造函数的名称。
标签: javascript php ajax