Wednesday, 12 September 2018

Load JSON data with jQuery

JSON data can be retrieved using AJAX from a server either using jQuery's .ajax() function or the shorthand $.getJSON() function. If you have retrieved a JSON string without having jQuery decode it automatically using one of these functions, the string can also be parsed into a regular data array using the $.parseJSON() function.

$.getJSON()

The easiest way to load some JSON data in jQuery is with the $.getJSON() function and using the callback to do something with the data. If the URL to get the JSON data is at /json/somedata.json then it can be retrieved and something done with it like so:
$.getJSON('/json/somedata.json', function(data) {
    // do something with the data here
});

$.ajax()

The above is a shortcut to the $.ajax() method. If you needed to set some of the other AJAX properties use the $.ajax() function instead. The following is the equivilent of the above:
$.ajax({
    dataType: 'json',
    success: function(data) {
        // do something
    },
    url: '/json/somedata.json'
});

$.parseJSON();

Finally, a JSON encoded string can be converted to a Javascript array using $.parseJSON(). If "string" in the example below contains a JSON string it can be converted to an array like so:
data = $.parseJSON(string);
The string could potentially be retrived using AJAX from the server as plain text, and then converted to an array like this, although normally you would use the dataType 'json' and leave it up to jQuery to do it for you:
$.ajax({
    dataType: 'text',
    success: function(string) {
        data = $.parseJSON(string);
        // do something
    },
    url: '/json/somedata.json'
});

Encoding JSON data with PHP

This post has been followed up showing how to load JSON data with jQuery, PHP and MySQL.

Related posts:

0 comments:

Post a Comment