Home  >  Article  >  Web Front-end  >  2 ways to obtain json data asynchronously with jQuery_jquery

2 ways to obtain json data asynchronously with jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 16:38:241271browse

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"
}

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>

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>

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.

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