JSON 是一种比较方便的数据形式,下面使用$.getJSON方法,实现获得JSON数据和解析,都挺方便简单的。从http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=? 这个地址得到JSON数据 并且分析里面的结构,生成图片和相关链接等:
01
|
$( function (){
|
02
|
var url= "http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?"
|
03
|
//使用getJSON方法取得JSON数据
|
04
|
$.getJSON(
|
05
|
url,
|
06
|
//处理数据 data指向的是返回来的JSON数据
|
07
|
function (data){
|
08
|
//生成标题和标题连接
|
09
|
var tit= "<a href='" + data.link + "'>" +data.title + "<\/a>" ;
|
10
|
$( "h1" ).html(tit);
|
11
|
//出现在指定位置H1 内
|
12
|
$( "#ginfo" ).find( "p" ).eq(0).html(data.modified);
|
13
|
$( "#ginfo" ).find( "p" ).eq(1).html(data.generator);
|
14
|
var lis= "" ;
|
15
|
//li 列表项目
|
16
|
$(data.items).each( function (i,ite){
|
17
|
//遍历JSON数据得到所需形式
|
18
|
lis+= "<li>" ;
|
19
|
lis+= "<a href='" + ite.link + "'><img src='" +ite.media.m + "' title='" + ite.title + "'><\/><\/a>" ;
|
20
|
lis+= "<div>" ;
|
21
|
lis+=ite.description;
|
22
|
lis+= "<\/div><\/li>" ;
|
23
|
})
|
24
|
$( "ul" ).html(lis);
|
25
|
//将遍历出来的数据呈现在所需位置
|
26
|
$( "li" ).hover( function (){$( this ).addClass( "hov" )}, function (){$( this ).removeClass( "hov" )});
|
27
|
}
|
28
|
)
|
29
|
})
|
HTML:
1
|
< div class = "main" >
|
2
|
< div class = "ginfo" id = "ginfo" >
|
3
|
< h1 ></ h1 >
|
4
|
< p ></ p >
|
5
|
< p ></ p >
|
6
|
</ div >
|
7
|
< ul >
|
8
|
</ ul >
|
9
|
</ div >
|
最后说一下JSON数据的格式,其实它就是个文本文件,可以方便的解析,也可以直接查看。
01
|
({
|
02
|
"title" : "Recent Uploads tagged cat" ,
|
03
|
"link" : "http://www.flickr.com/photos/tags/cat/" ,
|
04
|
"description" : "" ,
|
05
|
"modified" : "2009-08-03T01:50:45Z" ,
|
06
|
"generator" : "http://www.flickr.com/" ,
|
07
|
"items" {
|
08
|
"title" : "DSC06844" ,
|
09
|
"link" : "http://www.flickr.com/photos/g_bugel/3783605340/" ,
|
10
|
"media" : { "m" : "http://farm3.static.flickr.com/2638/3783605340_a3cfc9eeb9_m.jpg" },
|
11
|
"date_taken" : "2009-07-06T07:27:59-08:00" ,
|
12
|
"description" : "<p><a href=\"http://www.flickr.com/people/g_bugel/\">g.bugel<\/a> posted a photo:<\/p> <p><a href=\"http://www.flickr.com/photos/g_bugel/3783605340/\" title=\"DSC06844\"><img src=\"http://farm3.static.flickr.com/2638/3783605340_a3cfc9eeb9_m.jpg\" width=\"240\" height=\"180\" /><\/a><\/p> " ,
|
13
|
"published" : "2009-08-03T01:50:45Z" ,
|
14
|
"author" : "nobody@flickr.com (g.bugel)" ,
|
15
|
"author_id" : "38658309@N00" ,
|
16
|
"tags" : "china cat feline beijing 2009 chinalab chinalab2009"
|
17
|
18
|
},{......});
|
热门源码