使用getJSON()方法异步加载JSON格式数据

本文介绍了如何使用getJSON方法进行Ajax异步请求,从服务器获取JSON格式数据,并在数据成功返回后进行解析,将内容展示在网页上。通过指定url参数为数据源地址,可选data参数发送额外数据,以及定义callback回调函数处理响应。
使用getJSON()方法异步加载JSON格式数据

使用getJSON()方法可以通过Ajax异步请求的方式,获取服务器中的数组,并对获取的数据进行解析,显示在页面中,它的调用格式为:

jQuery.getJSON(url,[data],[callback])$.getJSON(url,[data],[callback])

其中,url参数为请求加载json格式文件的服务器地址,可选项data参数为请求时发送的数据,callback参数为数据请求成功后,执行的回调函数。

 

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3     <head>
 4         <title>使用getJSON()方法异步加载JSON格式数据</title>
 5         <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
 6     </head>
 7     <style>
 8         #divtest
 9         {
10             width: 282px;
11         }
12         #divtest .title
13         {
14             padding: 8px;
15             background-color:Blue;
16             color:#fff;
17             height: 23px;
18             line-height: 23px;
19             font-size: 15px;
20             font-weight: bold;
21         }
22         ul
23         {
24             float: left;
25             width: 280px;
26             padding: 5px 0px;
27             margin: 0px;
28             font-size: 14px;
29             list-style-type: none;
30         }
31         ul li
32         {
33             float: left;
34             width: 280px;
35             height: 23px;
36             line-height: 23px;
37             padding: 3px 8px;
38         }
39         .fl
40         {
41             float: left;
42         }
43         .fr
44         {
45             float: right;
46         }
47     </style>
48     <body>
49         <div id="divtest">
50             <div class="title">
51                 <span class="fl">我最喜欢的一项运动</span> 
52                 <span class="fr">
53                     <input id="btnShow" type="button" value="加载" />
54                 </span>
55             </div>
56             <ul></ul>
57         </div>
58         
59         <script type="text/javascript">
60             $(function () {
61                 $("#btnShow").bind("click", function () {
62                     var $this = $(this);
63                     $.getJSON("./sport.json",function(data){
64                         $this.attr("disabled", "true");
65                         $.each(data,function(index,sport){
66                             //if(index==3)
67                             $("ul").append("<li>" + sport["name"] + "</li>");
68                         });
69     
70                     });
71                 })
72             });
73         </script>
74     </body>
75 </html>
View Code
1 [{"name":"足球"},{"name":"篮球"},{"name":"乒乓球"},{"name":"排球"}]
View Code

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值