简体   繁体   English

解码使用Javascript从PHP检索到的json对象

[英]Decoding json object retrieved from PHP in Javascript

I am having trouble using the json object echoed from php to javascript. 我在使用从php回显到javascript的json对象时遇到了麻烦。 In the php file I define 在php文件中,我定义了

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

and then in javascript file I want to access this object. 然后在javascript文件中我要访问该对象。

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

I get undefined for data["a"] and an error for JSON.parse. 我没有为data [“ a”]和JSON.parse定义一个错误。 How should I use the returend data? 我应该如何使用后退数据?

Based on your comment (echoing several json strings), you should do the following: 根据您的评论(回显几个json字符串),您应该执行以下操作:

  1. Initialize an empty results array; 初始化一个空的结果数组;
  2. Read your file and put it in an array or object using json_decode() ; 读取文件,然后使用json_decode()将其放入数组或对象中;
  3. Add this array / object to your results array; 将此数组/对象添加到结果数组;
  4. At the end, use json_encode() to encode and echo out your results array. 最后,使用json_encode()编码并回显结果数组。

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

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

The problem might be that PHP is returning a string that looks like JSON. 问题可能是PHP返回的字符串看起来像JSON。

In JS it might help to JSON.parse(data) to convert from string to JSON object, then you can access it. 在JS中,它可能有助于JSON.parse(data)从字符串转换为JSON对象,然后您可以访问它。

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

您需要将json_encode或在javascript中解析

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM