2016-06-13 20 views
0

我只是不能让getCategory函数返回除undefinedfalse以外的任何东西。我已经在控制台中走过了,所有的数据都在那里。我仍然在最好的方式不确定,使函数调用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 }选项

+1

你需要一个回调添加到'getCategory'函数。 Ajax的定义是异步调用(“异步JavaScript和XML”的缩写),但不能使其同步。 –

+0

嗯,是的,但是:http://stackoverflow.com/questions/1478295/what-does-async-false-do-in-jquery-ajax –

+1

Stapal:我试过了,但是它被暂时解除了 –

回答

0

这里的问题是有许多拿到电话后,首先获得通过调用“的getCategory”发生。

我们可以修改逻辑,以便锚标记中的数据一旦获得与该锚标记的调用相关的加载就完成了。

修改锚标签给它一个唯一的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(''); 
    } 
} 
+0

我仍然得到undefined返回... –

+2

@ a-windett,的确,但你不应该依赖返回值,因为你得到它*之前* Ajax响应可用。这个动作发生在'done'函数中。 – trincot

+0

我们不需要返回任何东西。我修改了我的答案 – Don