为什么这个json_encode返回字符串而不是对象?

时间:2016-07-19 10:02:49

标签: php

我正在使用 select FORMAT(createDate,'yyyyMMdd') AS date, SUM(bb_cnt) AS 'Broadband Service', SUM(tel_cnt) AS 'Telephone Service', SUM(bb_tel_cnt) AS 'Broadband & Telephone Service', from (select createDate, CASE WHEN ServicePlan LIKE '%Broadband Service%' then 1 else 0 end AS bb_cnt, CASE WHEN ServicePlan LIKE 'Telephone Service%' OR ServicePlan LIKE '%, Telephone Service%' then 1 else 0 end AS tel_cnt, CASE WHEN ServicePlan LIKE '%Broadband & Telephone Service%' then 1 else 0 end AS bb_tel_cnt, from EFormRegisterationData ) a group by FORMAT(createDate,'yyyyMMdd') order by 1; 将关联数组转换为JSON格式。但是当我尝试打印从这个PHP文件通过Ajax访问的 json_encode 的属性时,它会显示 undefined 。当我检查数据类型时,它返回字符串

data

为什么会这样?如何通过此字符串访问$elem1= "<div class='menuitems'> <div class='menu1'>".$row['name']."<span class='srno'>".$row['srno']."</span></div> <div class='menu2'>".$row['email']."</div> <div class='menu3'>".$row['password']."<span class='cross'>X</span></div> <div class='clear'></div> </div>"; $elem2=$row['category']; $array=array( "elem1"=>"$elem1", "elem2"=>"$elem2" ); echo json_encode($array); elem1

1 个答案:

答案 0 :(得分:0)

HTTP响应始终为字符串数据类型。您需要先解析JSON才能使用。有两种方法。你需要使用:

$.getJSON(url, function (data) {
    typeof data; // object
});

与之相反:

$.get(url, function (data) {
    typeof data; // string
});

如果您使用上述内容,则需要使用:

$.get(url, function (data) {
    typeof data; // string
    data = JSON.parse(data);
    typeof data; // object
});
  

注意:我正在使用jQuery的AJAX。转换是非常具体的纯JavaScript。