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.

mythicalprogrammer
  • 4,647
  • 6
  • 35
  • 42

3 Answers3

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
Luke Dennis
  • 14,212
  • 17
  • 56
  • 69
0

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

VDVLeon
  • 1,393
  • 1
  • 15
  • 26
0

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

Ciprian Mocanu
  • 2,166
  • 3
  • 25
  • 44