Home > Web Front-end > JS Tutorial > How Can I Iterate Through and Display JSON Data Using jQuery?

How Can I Iterate Through and Display JSON Data Using jQuery?

Susan Sarandon
Release: 2024-12-02 22:46:13
Original
781 people have browsed it

How Can I Iterate Through and Display JSON Data Using jQuery?

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);
        }
    });
});
Copy after login

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" }
]
Copy after login

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
            }));
        });
    }
});
Copy after login

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
        }));
    });
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template