我只是不能让getCategory
函数返回除undefined
或false
以外的任何东西。我已经在控制台中走过了,所有的数据都在那里。我仍然在最好的方式不确定,使函数调用syncronosly如何让这个Ajax调用不是异步的?
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 }
选项
你需要一个回调添加到'getCategory'函数。 Ajax的定义是异步调用(“异步JavaScript和XML”的缩写),但不能使其同步。 –
嗯,是的,但是:http://stackoverflow.com/questions/1478295/what-does-async-false-do-in-jquery-ajax –
Stapal:我试过了,但是它被暂时解除了 –