Home >Web Front-end >JS Tutorial >How to Parse and Display JSON Data Using jQuery's AJAX or $.getJSON?

How to Parse and Display JSON Data Using jQuery's AJAX or $.getJSON?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-07 21:53:15879browse

How to Parse and Display JSON Data Using jQuery's AJAX or $.getJSON?

Parsing JSON Data with jQuery/JavaScript

When utilizing AJAX to retrieve JSON data, it is necessary to ensure that the Content-Type header is correctly set to application/json. If this is not the case, you must specify the data type as 'json' manually.

To iterate over the JSON data and display each name within a div, you can employ the $.each() function:

$.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 utilize the $.getJSON method:

$.getJSON("/functions.php", { get_param: "value" }, function (data) {
  $.each(data, function (index, element) {
    $("body").append($("<div>", {
      text: element.name
    }));
  });
});

The above is the detailed content of How to Parse and Display JSON Data Using jQuery's AJAX or $.getJSON?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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