开发者

JSON concept with javascript & PHP

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 s开发者_开发问答cript, 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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜