源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

jQuery实现异步获取json数据的2种方式

  • 时间:2021-05-18 18:29 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:jQuery实现异步获取json数据的2种方式
本文实例讲述了jQuery实现异步获取json数据的2种方式,在web程序开发中非常具有实用价值。分享给大家供大家参考之用。具体方法如下: 通常来说,jQuery异步获取json数据有2种方式,一个是$.getJSON方法,一个是$.ajax方法。本文就来实现使用这2种方式异步获取json数据,然后追加到页面。 在根目录下创建data.json文件:
{
 "one" : "Hello",
 "two" : "World"
}
 
[b]一、通过$.getJSON方法获取json数据[/b]
 <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>
[img]http://files.jb51.net/file_images/article/201408/2014829111941178.png?201472911205[/img]   [b]二、通过$.ajax方法获取json数据[/b]
 <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>

总结:[b]使用$.getJSON方法和$.ajax方法都能达到相同的效果,但是,如果想对异步获取的过程有更细节的控制,推荐使用$.ajax方法。[/b] [b]

PS:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:[/b] 在线JSON代码检验、检验、美化、格式化工具: [url=http://tools.jb51.net/code/json]http://tools.jb51.net/code/json[/url] JSON在线格式化工具: [url=http://tools.jb51.net/code/jsonformat]http://tools.jb51.net/code/jsonformat[/url] 在线XML/JSON互相转换工具: [url=http://tools.jb51.net/code/xmljson]http://tools.jb51.net/code/xmljson[/url] json代码在线格式化/美化/压缩/编辑/转换工具: [url=http://tools.jb51.net/code/jsoncodeformat]http://tools.jb51.net/code/jsoncodeformat[/url] 在线json压缩/转义工具: [url=http://tools.jb51.net/code/json_yasuo_trans]http://tools.jb51.net/code/json_yasuo_trans[/url] C语言风格/HTML/CSS/json代码格式化美化工具: [url=http://tools.jb51.net/code/ccode_html_css_json]http://tools.jb51.net/code/ccode_html_css_json[/url]

相信本文所述对大家的jQuery程序设计有一定的借鉴价值。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部