2012-03-09 25 views
1

響應我試圖讓在組合函數返回與Facebook API reqeust。得到FB API JavaScript程式

var g_ret = true; 

function uploadImagesFbCounter(anz){ 
    var gid=''; 
    $("div[id ^= 'gallerydetail']").each(function (i) { 
     gid = this.id.split('-'); 
     gid = parseInt(gid[1]); 
    }) 
    if(gid==0) return true; 

    FB.api('/me', function(response) { 

   //console.log(response); 
   var uid = response.id; 

     if(!anz){ 
      g_ret = $.ajax({ 
       type: "POST", 
       async:false, 
       url: "api/gallerie_anz_speich.php", 
       data: "uid="+uid+"&op=get&gid="+gid 
      }); 

      if(g_ret.response >= 20) { 
       g_ret = false; 
      } 
     } else { 
      g_ret = $.ajax({ 
       type: "POST", 
       async:false, 
       url: "api/gallerie_anz_speich.php", 
       data: "uid="+uid+"&op=set&gid="+gid 
      }); 
      //console.log(g_ret.response); 
      g_ret = '<span style="padding:0 5px;">Noch '+(20-g_ret.response)+'Fotos</span>'; 
      console.log(g_ret); 
     } 
    }); 

    return g_ret; 
} 

我做了什麼,我得到一個空的答覆....請幫助!

回答

1

充分利用Facebook的服務器上的用戶信息是異步的。這意味着,您在FB.api()之後編寫的任何代碼都不會等待Facebook做出迴應。您的瀏覽器不會僅僅是等待Facebook的服務器。這與AJAX相同,我相信你很熟悉,因爲我看到你在代碼中使用它。

常見的方式「得到一個返回值」從異步服務器請求是使用一個回調函數。

function uploadImagesFbCounter(anz, onSuccess){ 
    var gid=''; 
    $("div[id ^= 'gallerydetail']").each(function (i) { 
     gid = this.id.split('-'); 
     gid = parseInt(gid[1]); 
    }) 
    if(gid==0) return true; 

    FB.api('/me', function(response) { 

     //console.log(response); 
     var uid = response.id; 

     if(!anz){ 
      g_ret = $.ajax({ 
       type: "POST", 
       async:false, 
       url: "api/gallerie_anz_speich.php", 
       data: "uid="+uid+"&op=get&gid="+gid 
      }); 

      if(g_ret.response >= 20) { 
       g_ret = false; 
      } 
     } else { 
      g_ret = $.ajax({ 
       type: "POST", 
       async:false, 
       url: "api/gallerie_anz_speich.php", 
       data: "uid="+uid+"&op=set&gid="+gid 
      }); 
      //console.log(g_ret.response); 
      g_ret = '<span style="padding:0 5px;">Noch '+(20-g_ret.response)+'Fotos</span>'; 
      console.log(g_ret); 
     } 

     onSuccess(g_ret); 
    }); 

} 


uploadImagesFbCounter(
    whateverAnzIs, 
    function(g_ret) { 
     console.info(g_ret); 
    } 
); 
+0

感謝你有很大的幫助:) – 2012-03-10 19:39:00

+0

您還需要你的$就成功回調調用的onSuccess。我不知道jQuery,所以你必須弄清楚。 – JoJo 2012-03-10 23:30:54

3

您正在使用的API是異步。你不能像你那樣從你的函數中返回一個值;在這種情況下,這是不可能的。

相反,寫你的API,以便客戶通過它可調用的函數。在Facebook API回調中,您可以調用該函數並將它傳遞給「g_ret」字符串。

function uploadImagesFbCounter(anz, callback){ 
    // ... 
    FB.api('/me', function(response) { 
    // ... 
    callback(g_ret); 
    }); 
} 

然後當你調用你的函數,而不是:

var result = uploadImagesFbCounter(whatever); 
// ... do something with result ... 

你可以這樣做:

uploadImagesFbCounter(whatever, function(result) { 
    // ... do something with result ... 
}); 
+0

有你的axample? – 2012-03-09 16:14:21

+0

我剛剛更新了基本思路的答案。我會再添加一點。 – Pointy 2012-03-09 16:15:51