How to get JSON from the Blogger API filtered by category
I am trying to get list of recent posts from a blog filtered by category completely on the client-side using jQuery. I'm really close and there have been a lot of posts here at stackoverflo开发者_如何学Gow which have been immensely helpful. Here is what I have so far...
<script type="text/javascript">
$(document).ready(function () {
BloggerImporter.getPosts();
});
var BloggerImporter = {
getPosts: function () {
var feedURL = "http://blog.mild.net/feeds/posts/default";
var paras = {
alt: 'json-in-script'
};
$.ajax({
url: feedURL,
type: 'get',
dataType: "jsonp",
success: BloggerImporter.onGotPostData,
data: paras
});
},
onGotPostData: function (data) {
var feed = data.feed;
var entries = feed.entry || [];
var filteredEntries = $.grep(entries, function (value) {
return value.category == 'Mild.Net'
});
$("#blogTemplate").tmpl(filteredEntries).appendTo("#posts");
}
}
</script>
Now, the problem is that each entry can have more than one category. So, in that jQuery grep function above, "category" is an array of objects, where each object has a "term" property. I need to filter by that "term" property, returning all the entries where that term property equals "Mild.Net".
How do I do that?
Why you don't simply run through all the categories?
var filteredEntries = $.grep(entries, function (value) {
if( ! value.category ) {
return false;
}
for(var i in value.category) {
if(value.category[i].term == 'Mild.Net') {
return true;
}
}
return false;
});
Or even simpler (I'm not sure about portability in this case):
var filteredEntries = $.grep(entries, function (value) {
return !value.category ? false : value.category.some(function(category) {
return category.term == 'Mild.Net';
});
});
精彩评论