2012-04-25 68 views
0

當用戶進入特定的.php頁面時,我會用FB.ui發送一個請求。如何用Javascript sdk進入頁面發送FB請求?

我使用這個腳本異步加載的JavaScript SDK:

<div id="fb-root"></div> 
<script> 
window.fbAsyncInit = function() { 
FB.init({ 
    appId  : 'YOUR_APP_ID', // App ID 
    channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File 
    status  : true, // check login status 
    cookie  : true, // enable cookies to allow the server to access the session 
    xfbml  : true // parse XFBML 
}); 

// Additional initialization code here 
}; 

// Load the SDK Asynchronously 
(function(d){ 
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; 
if (d.getElementById(id)) {return;} 
js = d.createElement('script'); js.id = id; js.async = true; 
js.src = "//connect.facebook.net/en_US/all.js"; 
ref.parentNode.insertBefore(js, ref); 
}(document)); 

function sendRequestToRecipients(user_id) { 
    FB.ui({method: 'apprequests', 
     message: 'My Great Request', 
     to: user_id, 
    }, requestCallback); 
    } 
</script> 

然後,我嘗試調用函數sendRequestToRecipients()用的onLoad功能,在標籤內:

<body onLoad="sendRequestToRecipients('0000'); return false;"> 

但我收到2錯誤「意外的標識符」,沒有任何反應。

另外,如果我從身體中刪除的onload和我手動調用sendRequestToRecipients功能與按鈕

<input type="button" 
    onclick="sendRequestToRecipients('0000'); return false;" 
    value="Send" 
    /> 

一切順利完美!

任何幫助?

回答

2

您不能從加載事件中調用該函數,因爲您只能在facebook sdk完成加載和初始化後才發出api請求。

它應該是:

<script> 
    window.fbAsyncInit = function() { 
     FB.init({ 
      appId  : 'YOUR_APP_ID', // App ID 
      channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File 
      status  : true, // check login status 
      cookie  : true, // enable cookies to allow the server to access the session 
      xfbml  : true // parse XFBML 
     }); 

     sendRequestToRecipients("USER_ID"); 
    }; 

    // Load the SDK Asynchronously 
    (function(d){ 
     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; 
     if (d.getElementById(id)) {return;} 
     js = d.createElement('script'); js.id = id; js.async = true; 
     js.src = "//connect.facebook.net/en_US/all.js"; 
     ref.parentNode.insertBefore(js, ref); 
    }(document)); 

    function sendRequestToRecipients(user_id) { 
     FB.ui({method: 'apprequests', 
      message: 'My Great Request', 
      to: user_id, 
     }, requestCallback); 
    } 
</script> 

請注意,我在window.fbAsyncInit回調方法稱爲sendRequestToRecipients,在FB.init後。