I am using PHP, jQuery, and JSON. Now I need to know how to parse the jQuery data in JavaScript.
load.php
<?php ... $json =json_encode($array); ?>
It returns jQuery by the following data.
[{'name':'STA','distance':'250','code':25}, {'name':'GIS','distance':'500','code':45}]
jQuery code
$.getJSON('load.php', function(json){ // Access object var a = json; pass(a); });
Now I need to pass the JSON (a) to JavaScript defined in file my.js:
var myjson = {}; function pass(a) { myjson = a; //Here, how do I get name, and distance, code. //I have tried 'alert(myjson.name)'. It returns undefined. }
What changes should I make to my logic?
You have an array of JSON objects, so you need to loop through the array to get each individual object:
Or, if you want to do it the jQuery way:
Both examples will give you an alert with ‘STA’ followed by ‘GIS’.
In addition to this, as pointed out by OIS, you’re trying to read the wrong variable in your code. The JSON should be in variable named
a.