[英]How can I make this ajax call not asynchronous?
我只是无法获得getCategory
函数来返回除undefined
或false
之外的任何内容。 我已逐步进入控制台,所有数据均已存在。 我仍然不确定使函数同步调用的最佳方法
function getCategory(url) {
if ( url ) {
let message = false
$.ajax({
url: url,
global: false,
type: 'GET',
dataType: 'json',
}).done( function(data) {
message = `<a class="post__category post__link" href="${data[0].link}">${data[0].name}</a>`
return message
})
} else {
return ''
}
}
function posts() {
$.get(WPPosts, data => {
data.forEach( d => {
const excerpt = d.excerpt.rendered.substr(0, characterCount)
const featuredImage = d._links['wp:featuredmedia']
const featuredImageURL = featuredImage ? featuredImage[0].href : ''
const terms = d._links['wp:term']
const category = terms.filter( term => term.taxonomy === 'category')
const categoryURL = category[0].href
let post = `<article class="column">
<div class="decoration decoration__paper decoration__tape decoration__tape--left text-center post">
<a href="${d.link}">
${ getFeaturedImage(featuredImageURL) }
</a>
<h2 class="post__title">${d.title.rendered}</h2>
<p>
${d.date_gmt}
${ getCategory(categoryURL) }
</p>
<div class="post__excerpt">
${excerpt}... <a class="post__link" href="${d.link}">Read more</a>
</div>
</div>
</article>`
post = $.parseHTML( post )
postsWrapper.append(post)
});
})
}
我试图避免使用{ async: false }
选项
这里的问题是,在第一个get调用之后,“ getCategory”发生了许多get调用。
我们可以修改逻辑,以便在完成与该锚定标记相关的调用后,加载锚定标记内的数据。
修改锚标记以为其赋予唯一的ID :(使用您可能想要的任何ID)
<a href="${d.link}" id="${d.link}">
Loding ..${ getFeaturedImage(featuredImageURL,${d.link}) }
</a>
然后修改函数以读取id:
function getCategory(url,id) {
if ( url ) {
let message = '';
$.ajax({
url: url,
global: false,
type: 'GET',
dataType: 'json',
}).done( function(data) {
message = `<a class="post__category post__link" href="${data[0].link}">${data[0].name}</a>`
$("#"+id).html(message ); // append data to anchor tag rather than returning.
})
} else {
$("#"+id).html('');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.