2016-06-13 23 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