2

I need someone to shed some light on this subject.

When a person do an AJAX call, that call a php script which echo out json_encode stuff, so that the javascript can mess around with it. Note: Assuming we set the header to json in the php script.

The data that the javascript receive from the php script, do we have to parse it using eval or json's library? Edit: Is it because it treats the data recieved from the php file as text and not as javascript?

Can we use the javascript dot-notation on the data that the php script returned? Or does this data have to some how be converted to a javascript object before we can use dot-notation?

Thank you in advance.

3 Answers 3

6

JSON is merely a string, which happens to conform to Javascript's syntax for objects (hence the abbreviation: JavaScript Object Notation.)

To convert it to a Javascript object, you can use the eval function, but for greater security, it's recommended to use the JSON object included in modern browsers, or a function provided by your Javascript library of choice:

var json = '{"thing":1, "thang":"two"}';

var obj1 = eval('('+json+')'); // easier, less secure
var obj2 = JSON.parse(json); // secure, but doesn't work everywhere
var obj3 = jQuery.parseJSON(json); // secure, works everywhere

Many libraries will also handle the conversion for you as part of the Ajax request. Here's how jQuery does it:

jQuery.get('http://domain.com/path/to/request', function(obj)
{
    // string is automatically converted to an object,
    // usable as array or with dot notation
    alert(obj.thing);
    alert(obj['thang']);
},
'json'); // indicates that we are requesting json and not html
1
  • 2
    Technically, it's JavaScript Object Notation. Commented Feb 20, 2011 at 22:22
0

You can always use a library like jQuery, Mootools, Prototype, etc. for the decoding JSON text to Javascript variables..

0

JSON is something like serialize from PHP :) It's a way to transform string to object and back :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.