Flickr是雅虎旗下的一家图片分享网站,拥有庞大的数据图片资源,幸运的是,它也为开发人员提供了Api接口,使得可以通过使用Api接口就能使用到大量的图片资源。下面链接是其提供的官方Api文档。
https://www.flickr.com/services/api/
下面使用js写的一个简单的图片搜索应用。使用了flickr提供的一个名为flickr.photos.search的方法,依据其官方文档提供的url格式,如下:
https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
or
https://farm{farm-id}.staticflickr.com/{server-id }/{id}_{secret}_[mstzb].jpg
or
https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{o-secret}_o.(jpg |gif|png)
以第一个为例,需要获得四个参数,分别为farm-id,server-id,id,secret,这里需要特别注意的是,我们请求访问回传的内容是json格式,如下:
jsonFlickrApi({"photos":{"page":1,"pages":66467,"perpage":5,"total":"332335","photo":[{"id":"25836143290","owner":"139253015@N05","secret":"d1bbf8d41d","server":"1487","farm":2,"title":"Smile","ispublic":1,"isfriend":0,"isfamily":0},{"id":"26016445532","owner":"132193565@N08","secret":"aaa65c778d","server":"1593","farm":2,"title":"Run","ispublic":1,"isfriend":0,"isfamily":0},{"id":"25836085550","owner":"24406007@N05","secret":"4d99856c72","server":"1656","farm":2,"title":"","ispublic":1,"isfriend":0,"isfamily":0},{"id":"26016393512","owner":"128056224@N03","secret":"a452c7fac6","server":"1494","farm":2,"title":"_04_5372-Modifica","ispublic":1,"isfriend":0,"isfamily":0},{"id":"26108884765","owner":"128056224@N03","secret":"d6383a61c6","server":"1449","farm":2,"title":"_04_5372-2","ispublic":1,"isfriend":0,"isfamily":0}]},"stat":"ok"})
仔细分析以上内容,看来photos里面包含了需要的全部内容,在仔细往下看,需要的内容在photo的属性里面,特别说明一点,使用jQuery里面的$.getJSON()方法获得的是json对象而非字符串。当获取到回传的对象data是,根据以上分析,我们可以得出需要的属性分别为data.photos.photo.farm;data.photos.photo.server…(就不一一列举了);好到了这一步图片的url地址已经清晰,现在需要做的是就是把图片搜索给搞出来。
查阅flickr.method.search方法的参数说明,以下链接
https://www.flickr.com/services/api/flickr.photos.search.html
得出图片搜索是根据标签属性,tags来搜索,因此只需要把tags拼接到url中就可以了,当然,如果你有兴趣开发更有趣的图片搜索,也可以自己找出更多的属性来玩,该方法的属性多达几十个。
下面是博主写的js代码
``
$(function ()
{
$("#sub").click(function ()
{
$("#get").empty();
var search_word = $("#search_word").val();
var search_num = "per_page="+$("#search_number").val();
//url访问 $.getJSON("https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=ffd0006240c83a54d0148d665b6ea76d&tags=" + $("#search_word").val() + "&tag_mode=all&media=&in_gallery=&"+search_num+"&format=json&jsoncallback=?", function (data) {
//var obj = eval("(" + data + ")")
//var obj2 = JSON.parse(data);
$.each(data.photos.photo, function (i,photo)
{
//这边是图片src属性的拼接
$("
").attr("src", "https://farm" + photo.farm + ".staticflickr.com/" + photo.server + "/" + photo.id +"_"+photo.secret+ ".jpg")
.appendTo("#get")
})
})
})
})
``