Does jQuery have built in JSON support or must I use a plugin like jquery.json-1.3.min.js ?
+9
A:
Yes, absolutely it does. You can do something like:
$.getJSON('/foo/bar/json-returning-script.php', function(data) {
// data is the JSON object returned from the script.
});
VoteyDisciple
2009-08-11 14:30:52
thanks this is good to know, in my situation karim79's response is the way I need to do it though. +1 I wonder why they have a plugin for json if it is built in!?
jasondavis
2009-08-11 14:44:41
+9
A:
You can also use $.ajax and set the dataType option to "json":
$.ajax({
url: "script.php",
global: false,
type: "POST",
data: ({id : this.getAttribute('id')}),
dataType: "json",
success: function(json){
alert(json.foo);
}
}
);
Also, $.get and $.post have an optional fourth parameter that allows you to set the data type of the response, e.g.:
$.postJSON = function(url, data, callback) {
$.post(url, data, callback, "json");
};
$.getJSON = function(url, data, callback) {
$.get(url, data, callback, "json");
};
karim79
2009-08-11 14:38:54
this is the way I am trying to do it actually, I am getting a json response from an ajax call so this is perfect for my situation!
jasondavis
2009-08-11 14:42:38
A:
jQuery's JSON support is simplistic, throwing caution to the wind. I've used $.ajax
and then parse the response text with the json.org javascript library. It lexically parses to avoid using eval()
and possibly executing arbitrary code.
spoulson
2009-08-11 14:54:50
the reccomended json2.js from json.org actually does use eval. It just has some complicated sanitization code run through the json source first. There's a lexical parser as fallback, but it runs much slower, by all accounts.
Breton
2009-08-11 15:19:39
+1
A:
jQuery supports decoding JSON, but does not support encoding out-of-the-box. For encoding, you'll need a plugin, a separate library, or a browser that supports the JSON.stringify and JSON.parse commands natively.
jimbojw
2010-05-11 18:09:59