Home > Web Front-end > JS Tutorial > body text

2 ways to obtain json data asynchronously with jQuery_jquery

WBOY
Release: 2016-05-16 16:38:24
Original
1273 people have browsed it

The examples in this article describe two ways for jQuery to obtain json data asynchronously, which is of great practical value in web program development. Share it with everyone for your reference. The specific method is as follows:

Generally speaking, there are two ways for jQuery to asynchronously obtain json data, one is the $.getJSON method and the other is the $.ajax method. This article will use these two methods to asynchronously obtain json data and then append it to the page.

Create the data.json file in the root directory:

{
  "one" : "Hello",
  "two" : "World"
}
Copy after login

1. Obtain json data through the $.getJSON method

  <script src="Scripts/jquery-2.1.1.min.js"></script>
  <script type="text/javascript">
    $(function() {
      $.getJSON('data.json', function(data) {
        var items = [];
        $.each(data, function(key, val) {
          items.push('<li id="' + key + '">' + val + '</li>');
        });
        $('<ul/>', {
          'class': 'list',
          html: items.join('')
        }).appendTo('body');
      });
    });
  </script>
Copy after login

2. Obtain json data through $.ajax method

  <script src="Scripts/jquery-2.1.1.min.js"></script>
  <script type="text/javascript">
    $(function() {
      $.ajax({
        url: 'data.json',
        dataType: 'json',
        success: function(data) {
          var items = [];
          $.each(data, function(key, val) {
            items.push('<li id="' + key + '">' + val + '</li>');
          });
          $('<ul/>', {
            'class': 'list',
            html: items.join('')
          }).appendTo('body');
        },
        statusCode: {
          404: function() {
            alert("没有找到相关文件~~");
          }
        }
      });
    });
  </script>

Copy after login

Summary: Using the $.getJSON method and the $.ajax method can achieve the same effect. However, if you want to have more detailed control over the asynchronous acquisition process, it is recommended to use the $.ajax method.

I believe that what is described in this article has certain reference value for everyone’s jQuery programming.

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!