views:

1133

answers:

3

Dear all i am using php and JQuery, and JSON.Now i need to know how to parseThe JQuery data in javascript.

load.php

<?php

 ...
 $json =json_encode($array);


?>

It Returns jQuery by following data

 [{"name":"STA","distance":"250","code":25},
 {"name":"GIS","distance":"500","code":45}]

jQuery

  $.getJSON("load.php", function(json){
     // access object
    var a=json;
    pass(a);
    });

Now I need Pass the a Json to javascript defined in my.js

var myjson={};

function pass(a){

 myjson=a;

 //Here How to get name,and distance,code
 //I have Tried alert(myjson.name) returns undefined
}

Any one help me any changed to made in my logic?

+6  A: 

You have an array of json objects, so you need to loop through the array to get each individual object.

for(var x = 0; x < myjson.length; x++) {
    alert(myjson[x].name);
    // myjson[x].distance, myjson[x].code also available
}

or, if you want to do it the jQuery way...

jQuery.each(myjson, function(x) {
    alert(myjson[x].name);
});

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.

Paolo Bergantino
+1  A: 

You try to use a variable named json which is not defined in the scope of your function. Instead you have to use the argument named a.

function pass(a) {
   var i;
    while(i = a.pop()) {
        alert(i.name + " " + i.distance);
    }
}
OIS
Is it Not possible To Transfer all JSON object from jQuery to javscript.So that all manipulation with javascript ,Any idea?
venkatachalam
Im sorry, but you have to rephrase that. I dont understand how you want to use the code?
OIS
A: 

How are you intending on using the json data?

The object returned will contain an array of values (based on your example json code.)

Gavin