我会查询flickr.photos.search并使用返回的 JSON 来构建将作为 img 标签的 src 值的 URL。这是一个如何使用 jQuery.getJSON() 的示例。
首先,您需要在此处注册您的应用并获取 API 密钥。
获得 API 密钥后,这里有一个基本演示,说明如何搜索 API、返回一个结果并在 img 标签中显示结果。为了简单起见,目前唯一的错误处理是获取 JSON 失败。请注意,该演示需要 jQuery:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Basic Flickr Image Search</title>
</head>
<body>
<label for="query">Search Flickr:</label>
<input id="query" type="text" placeholder="Dog">
<input id="submit" type="submit">
<div id="container"></div>
<script src="jquery.min.js"></script>
<script src="app.js"></script>
</body>
</html>
JavaScript (app.js)
var query = $('#query');
var submit = $('#submit');
var container = $('#container');
submit.click(function() {
// Clear the previously displayed pic (if any)
container.empty();
// build URL for the Flickr API request
var requestString = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=";
// Replace XXXXXXXX with your API Key
requestString += "XXXXXXXX";
requestString += "&text=";
requestString += encodeURIComponent(query.val());
requestString += "&sort=relevance&media=photos&content_type=1&format=json&nojsoncallback=1&page=1&per_page=1";
// make API request and receive a JSON as a response
$.getJSON(requestString)
.done(function(json) {
// build URL based on returned JSON
// See this site for JSON format info: https://www.flickr.com/services/api/flickr.photos.search.html
var URL = "https://farm" + json.photos.photo[0].farm + ".staticflickr.com/" + json.photos.photo[0].server;
URL += "/" + json.photos.photo[0].id + "_" + json.photos.photo[0].secret + ".jpg";
// build the img tag
var imgTag = '<img id="pic" src="' + URL + '">';
// display the img tag
container.append(imgTag);
})
.fail(function(jqxhr) {
alert("Sorry, there was an error getting pictures from Flickr.");
console.log("Error getting pictures from Flickr");
//write the returned object to console
console.log(jqxhr);
});
});