Parsing JSON Data with jQuery / JavaScript
When working with web services or APIs, it's common to receive JSON data. Parsing this data into a usable format is necessary for displaying and manipulating the data on your web page.
Problem Statement:
Consider the following AJAX call that returns JSON data:
$(document).ready(function () { $.ajax({ type: 'GET', url: 'http://example/functions.php', data: { get_param: 'value' }, success: function (data) { var names = data; $('#cand').html(data); } }); });
The JSON data retrieved in the #cand div looks like this:
[ { "id": "1", "name": "test1" }, { "id": "2", "name": "test2" }, { "id": "3", "name": "test3" }, { "id": "4", "name": "test4" }, { "id": "5", "name": "test5" } ]
The question arises: how can we loop through this JSON data and display each name in a separate div?
Solution:
To parse JSON data correctly, we need to ensure that the server-side script sets the proper Content-Type: application/json response header. For jQuery to recognize the data as JSON, we need to specify dataType: 'json' in the AJAX call.
Once we have the correct data type, we can use the $.each() function to iterate through the data:
$.ajax({ type: 'GET', url: 'http://example/functions.php', data: { get_param: 'value' }, dataType: 'json', success: function (data) { $.each(data, function (index, element) { $('body').append($('<div>', { text: element.name })); }); } });
Alternatively, you can use the $.getJSON() method for a more concise approach:
$.getJSON('/functions.php', { get_param: 'value' }, function (data) { $.each(data, function (index, element) { $('body').append($('<div>', { text: element.name })); }); });
This will create a new div for each name in the JSON data and display it on the web page.
The above is the detailed content of How Can I Iterate Through and Display JSON Data Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!