Home  >  Article  >  Web Front-end  >  jQuery uses ajax to read local json files

jQuery uses ajax to read local json files

黄舟
黄舟Original
2017-10-31 10:50:012692browse

jsonFile

{
  "first":[
    {"name":"张三","sex":"男"},
    {"name":"李四","sex":"男"},
    {"name":"王武","sex":"男"},
    {"name":"李梅","sex":"女"}
  ]
}

js:

Method one:

$.ajax({
  url: "ceshi.json",//json文件位置
  type: "GET",//请求方式为get
  dataType: "json", //返回数据格式为json
  success: function(data) {//请求成功完成后要执行的方法 
    //each循环 使用$.each方法遍历返回的数据date
    $.each(data.first, function(i, item) {
      var str = &#39;<p>姓名:&#39; + item.name + &#39;性别:&#39; + item.sex + &#39;</p>&#39;;
      document.write(str);
    })
  }
})

Method two:

jQuery.getJSON() is jQuery .ajax()Short form of function

// jQuery.getJSON( url [, data ] [, success ] )
$.getJSON("ceshi.json", "", function(data) {
    //each循环 使用$.each方法遍历返回的数据date
    $.each(data.first, function(i, item) {
      var str = &#39;<p>姓名:&#39; + item.name + &#39;性别:&#39; + item.sex + &#39;</p>&#39;;
      document.write(str);
    })
});

The above is the detailed content of jQuery uses ajax to read local json files. 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