Ajax tip: Use JSON format
Hi all,
The benefit of JSON on other formats is that it is recognized natively by JavaScript. This is huge advantage because you don’t need to write a code for parsing an XML document to extract the data and get it throught the net. So it saves time and it is faster.
The JSON format is very simple:
{
"menu": "File",
"commands": [
{
"title": "New",
"action":"CreateDoc"
},
{
"title": "Open",
"action": "OpenDoc"
},
{
"title": "Close",
"action": "CloseDoc"
}
]
}
and you use the eval() JavaScript function to parse it.
var req = new XMLHttpRequest();
req.open("GET", "file.json", true);
req.onreadystatechange = myCode; // the handler
req.send(null);
The JavaScript handler:
function myCode()
{
if (req.readyState == 4)
{
var doc = eval('(' + req.responseText + ')');
}
}
