这样做的目的是自动将归因链接添加到博文中使用的图像。我有一个 demo set up here ,它会手动使用flickr.photos.getInfo
在图片上构建归因网址。
为此,我从CSS中的background-image
获取了照片ID并创建了API调用。我要做的是自动从background-image
网址中提取带照片的ID( 3990985751 ),以便在每个帖子上创建API调用。
CSS
.featured {
background-image:url('https://farm3.staticflickr.com/2613/3990985751_7ca0769f15_b.jpg');
}
HTML
<div class="featured">
<body>
<div class="featured">
<div id="featured-credit">
<p id="credits"></p>
</div>
</div>
</div>
的jQuery / JS
// Builds the URL to link in the image credit
function jsonFlickrApi (response) {
$("#credits").html('<a href="http://www.flickr.com/photos/'+response.photo.owner.nsid+'/'+response.photo.id+'/" target="blank">'+response.photo.title._content+"</a>");
}
// removes the CSS formatting for the featured image background URL
function extractUrl(input) {
return input.replace(/"/g,"").replace(/url\(|\)$/ig, "");
}
/* After all the scripts are loaded, send the featured photo to the Flickr API to get the JSON data */
<script src="https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=APIKEYHERE&photo_id=3990985751&format=json&jsoncallback=?"></script>
我在SO和其他网站上研究过一堆,我发现的其他解决方案都使用了配置文件URL,而我需要使用静态源URL。任何帮助表示赞赏。
答案 0 :(得分:1)
您是否尝试过对闪烁进行ajax调用?
$.ajax({
url: "https://api.flickr.com/services/rest/",
type: 'GET',
contentType: "application/json;charset=utf-8",
data:{
method: 'flickr.photos.getInfo',
api_key: 'c8c95356e465b8d7398ff2847152740e',
format: 'json',
photo_id: yourPhotoID,
},
success: function(data){
//data is the response from flickr
}
});
答案 1 :(得分:0)
我在上面评论过$.ajax
调用对我没有用,但我能够使用jQuery&#39; $.getJSON
方法解决它。 JS仅在下面:
// removes the CSS formatting for the featured image background URL
function extractUrl(input) {
return input.replace(/"/g,"").replace(/url\(|\)$/ig, "");
};
//Set a variable to hold the extracted URL & pass the string to the next function
bg = extractUrl($(".featured").css("background-image"))
extractPhotoId();
// This *really* ugly Regex pulls out the photo ID from the extracted URL and saves it in a variable
function extractPhotoId() {
photoId = bg.replace(/(.+\.[a-z]{2,4})\/(\d{3,5})\/(\d{7,15})(?:(?!ab).)*/ig, '$3');
}
// Constructed API url to use with the JSON request
var apiUrl = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=c8c95356e465b8d7398ff2847152740e&photo_id=" + photoId + "&format=json&jsoncallback=?";
// Call the Flickr API URL and apply the data to the source credit div
$.getJSON(apiUrl, function(data){
$("#credits").html('<a href="http://www.flickr.com/photos/'+data.photo.owner.nsid+'/'+data.photo.id+'/" target="blank">'+data.photo.title._content+"</a>");
});
如果你想在CSS中使用图像源来试用它,那么这是一个有用的 CodePen demo 。更改background-image
中的源网址后,您可能需要刷新页面以使其更新信用额度。