1
我正在使用WordPress REST API來檢索博客帖子,這一切都很好。我有一個初始的$.getJSON
調用來檢索相關的帖子,然後我通過$.each
以上的數據返回相關的HTML blob呈現給頁面。
但是,我有點卡住如何實現每個職位的類別列表。 posts端點只列出了類別ID,所以我需要以某種方式查詢類別端點,傳入ID以構建類別鏈接。 我可以在$.each
之內嵌入$.getJSON
調用以查詢該帖子的類別嗎?在如何構建這個方面掙扎。
這是我迄今爲止(相關代碼的只是提取片段):
var state = {
totalPages: null,
posts: [],
page: 1
}
getPostsByCategoryId: function getPostsByCategoryId(id, container) {
$.getJSON('/wp-json/wp/v2/posts?filter[cat]='+id+'&filter[orderby]=title&filter[order]=ASC&filter[posts_per_page]=4&page='+state.page+'', function(data, status, xhr) {
state.totalPages = xhr.getResponseHeader('X-WP-TotalPages');
$.each(data, function() {
var featuredImage = null;
var cats = this.categories;
var categories = [];
// // Loop over the categories
$.each(cats, function() {
$.getJSON('/wp-json/wp/v2/categories/13', function(data) {
var categoryItem = '<a class="category" href="' + data.link + '">' + data.name + '</a>';
categories.push(categoryItem);
});
});
var post = $('<div class="news"><div class="detail"><p class="postmeta"><a class="category" href="#">CATEGORIES</a></p><h3 class="title"><a href="' + this.link + '">' + this.title.rendered + '</a></h3><a href="' + this.link + '">View article</a></div></div>');
state.posts.push(post);
});
container.append(state.posts);
if (state.page == state.totalPages)
$('#loadmore').addClass('disabled');
state.page++;
});
return false;
}
謝謝:)
更新的代碼 - 無法讀取屬性呈現的不確定
getPostsByCategoryId: function getPostsByCategoryId(id, container) {
$.getJSON('/wp-json/wp/v2/posts?filter[cat]='+id+'&filter[orderby]=title&filter[order]=ASC&filter[posts_per_page]=4&page='+state.page+'', function(data, status, xhr) {
state.totalPages = xhr.getResponseHeader('X-WP-TotalPages');
$.each(data, function() {
var featuredImage = null;
var cats = this.categories;
var categories = [];
var requests = [];
// // Loop over the categories
$.each(cats, function() {
var xhr = $.getJSON('/wp-json/wp/v2/categories/13', function(data) {
var categoryItem = '<a class="category" href="' + data.link + '">' + data.name + '</a>';
categories.push(categoryItem);
});
requests.push(xhr);
});
$.when.apply($, requests).then(function() {
var post = $('<div class="news"><div class="detail"><p class="postmeta"><a class="category" href="#">CATEGORIES</a></p><h3 class="title"><a href="' + this.link + '">' + this.title.rendered + '</a></h3><a href="' + this.link + '">View article</a></div></div>');
state.posts.push(post);
});
});
container.append(state.posts);
blogPostLoader.toggleLoadingIcon($('.loading i'));
if (state.page == state.totalPages)
$('#loadmore').addClass('disabled');
state.page++;
});
return false;
}
你的問題是'$ .getJSON' *仍然是異步的,當ajax請求將在*稍後*完成時,你不能推送到外部數組,並期望值現在* *。 – adeneo
我是這麼想的,有沒有辦法鏈接成功函數來填充數組? –
也許這樣的事情? - > https://jsfiddle.net/cj4dad9a/ – adeneo