在Javascript中解码从PHP检索的json对象

时间:2014-05-15 22:15:12

标签: javascript php jquery json

我无法使用从php回显到javascript的json对象。在我定义的php文件中

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
echo($json);

然后在javascript文件中我想访问此对象。

$("#test_btn").click(function() {
                $.get("serverside.php", function(data, status) { 
                   console.log("data " , data["a"]); //undefined
                   console.log(JSON.parse(data)); // error
                });
            });

我未定义数据[" a"]和JSON.parse的错误。我该如何使用returend数据?

4 个答案:

答案 0 :(得分:3)

根据您的评论(回显几个json字符串),您应该执行以下操作:

  1. 初始化空结果数组;
  2. 使用json_decode();
  3. 读取您的文件并将其放入数组或对象中
  4. 将此数组/对象添加到结果数组中;
  5. 最后,使用json_encode()对结果数组进行编码和回显。

答案 1 :(得分:1)

在尝试访问JSON.parse(data)之前,您必须创建一个data['a'],然后从PHP发送一个标头,隐含地告诉浏览器数据输出将是一个JSON。

header ('Content-Type: application/json');

答案 2 :(得分:0)

问题可能是PHP返回的字符串看起来像JSON。

在JS中,它可能有助于JSON.parse(数据)从字符串转换为JSON对象,然后您可以访问它。

$("#test_btn").click(function() {
  $.get("serverside.php", function(data, status) {
    $json = JSON.parse(data);
    console.log("data " , $json["a"]); // should now return 1
  });
});

答案 3 :(得分:0)

你需要把json_encode或解析它在javascript中