Reputation: 48963
Does jQuery have built in JSON support or must I use a plugin like jquery.json-1.3.min.js ?
Upvotes: 9
Views: 2310
Reputation: 11042
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.
Upvotes: 1
Reputation: 21591
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.
Upvotes: 1
Reputation: 342655
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");
};
Upvotes: 9
Reputation: 37803
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.
});
Upvotes: 9