我會查詢flickr.photos.search並使用返回的JSON來構建將作爲img標記的src值的URL。這裏是一個例子,如何使用jQuery.getJSON()來做到這一點。
首先,您需要註冊您的應用程序並獲取API密鑰here。
一旦你有一個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);
});
});
謝謝!對我來說很好的答案,因爲我目前正在學習jQuery,所以我可以進入該代碼並進行更改...猜對方的答案也是有效的,但我現在不知道PHP。驚人! – youpielove