I am having trouble using the json object echoed from php to javascript. In the php file I define

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

and then in javascript file I want to access this object.

$("#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. How should I use the returend data?

有帮助吗?

解决方案

Based on your comment (echoing several json strings), you should do the following:

  1. Initialize an empty results array;
  2. Read your file and put it in an array or object using 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.

其他提示

You must make a JSON.parse(data) before attempting to access to data['a'], and send a header from PHP that implicitly say the browser that the data output is going to be a JSON.

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

The problem might be that PHP is returning a string that looks like JSON.

In JS it might help to JSON.parse(data) to convert from string to JSON object, then you can access it.

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

you need to put json_encode or parse it in javascript

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top