0

好吧,我已經把這個問題折磨了幾天。這就是問題所在:Facebook Graph異步回調問題

  1. 我使用Facebook的API檢索從特定相冊的圖片。
  2. 使用JCarouselhttp://sorgalla.com/projects/jcarousel/),我想動態添加從Facebook的圖片到傳送帶。
  3. 問題是,因爲Facebook API是異步,執行傳送帶的代碼部分需要信息(圖片URL),這些信息還不可用。

某種形式的解決方法是使用一個警告框強制延遲,這使得Facebook的API查詢「趕超」當你確認警報,你瞧,圖像出現旋轉木馬裏面!

反正根本無法解決這個問題。經過研究,我發現使用「Callback」函數解決了相似問題。

我是一名編程新手,所以任何幫助將非常感激。

我想修改這個頁面流的Facebook圖片: http://sorgalla.com/projects/jcarousel/examples/dynamic_javascript.html

另外,爲了使這項工作,你還需要的Facebook的Javascript SDK腳本

<script src="//connect.facebook.net/en_US/all.js"></script> 

您還需要jQuery的。

最後,下面是我的代碼的樣品,即不工作的部分:

$(document).ready(function() { 
//the below is an Asynchronous request to facebook 

FB.api('/232137976851458' + '/photos', function(response) { 
for (i=0;i<=response.data.length;i++) 
    { 
    mycarousel_itemList[i] = {url: response.data[i].picture, title: "2"}; 
    } 
}); 

//the alert below is used as a forced break to allow the api to stream the required information, if we remove this alert, the images refuse to load into the carousel 

alert("test"); 

//after the pictures are retrieved from the facebook API, the mycarousel_itemList array will be used to dynamically add the pictures into a carousel.....the code to instantiate the carousel is below 

jQuery('#mycarousel').jcarousel({ 
    size: mycarousel_itemList.length, 
    wrap: "circular", 
    itemLoadCallback: {onBeforeAnimation: mycarousel_itemLoadCallback} 
}); 

});

回答

0

感謝這麼多的快速回復後腰 - 上面沒有acually工作,但它確實給我一個想法,最終導致我找到解決方案。

當我將Caroussel的實例化放到For循環中時,它工作,因爲Carousel本身的尺寸是ammount,如果基於數組長度的項目在for循環中的每一步都重置,所以它覆蓋api異步請求的最新信息。這裏是工作答案:

FB.api('/232137976851458' + '/photos', function(response) { 
    for (i=0;i<=response.data.length;i++) 
    { 
     mycarousel_itemList[i] = {url: response.data[i].picture, title: "2"}; 

     jQuery('#mycarousel').jcarousel({ 
      wrap: "circular", 
      size: mycarousel_itemList.length, 
      itemLoadCallback: {onBeforeAnimation: mycarousel_itemLoadCallback} 
     }); 
    }  
}) 
+0

我很困惑。你所做的只是改變你的代碼和我的代碼之間'wrap'和'size'的順序。這有什麼不同? – DMCS 2012-04-17 20:05:37

+0

caroussel在for循環內引發,這是不同之處,現在就像一個魅力 – 2012-04-18 07:57:08

1

沒有警覺是必要的,如果你移動的jCarousel呼叫步入回調

FB.api('/232137976851458' + '/photos', function(response) { 
     for (i=0;i<=response.data.length;i++) 
     { 
      mycarousel_itemList[i] = {url: response.data[i].picture, title: "2"}; 
     } 

     jQuery('#mycarousel').jcarousel({ 
      size: mycarousel_itemList.length, 
      wrap: "circular", 
      itemLoadCallback: {onBeforeAnimation: mycarousel_itemLoadCallback} 
     }); 

    });