简体   繁体   中英

How to pass the right variable to a FB.ui script in a JqueryMobile multipage dynamically created html file

I'm using FB.ui to post to a Facebook user wall inside a Jquery multipage dynamically created?

function print_sharescript($values) {
echo "
<script> 
  FB.init({appId: \"$_SESSION[appId]\", status: true, cookie: true});
  function postToFeed() {
    // calling the API ...
    var obj = {
      method: 'feed',
      link: '$values[link]',
      picture: '$values[picture]',
      name: '$value[name]',
      caption: '$value[caption]',
      description: '$value[description]'
    };
    function callback(response) {
      // document.getElementById('msg').innerHTML = \"Post ID: \" + response['post_id'];
    }
    FB.ui(obj, callback);
  }
</script>
";
 }

 ... code ...
 foreach ($des=>$val) {
      // explode $val and fill the $values[$des][...] array ($des: from 0 to 10)
      print_sharescript($values[$des]);
      echo "// MY OUTPUT....";
      echo "<a onclick='postToFeed(); return false;'>Share</a>";
 }
 .... code ....

All runs fine except that the shared values are always the last array values. If I look at html code every script in the loop has its right value but the value in the FB Share popup are the wrong ones..

the problem I suppose is due to the obj variable. How could I correct the error?

If you look at the output of your PHP code, you should be able to see that the postToFeed javascript function definition is repeated. Because the function has the same name each time, the latest mention will overwrite all other definitions.

This is untested pseudo-PHP, but you might try something like this:

// You could actually move this into your .js or .html file instead
function print_sharescript($values) {
echo "
<script> 
  FB.init({appId: \"$_SESSION[appId]\", status: true, cookie: true});
  function postToFeed(obj) {
    obj.method = 'feed';
    function callback(response) {
      // document.getElementById('msg').innerHTML = \"Post ID: \" + response['post_id'];
    }
    FB.ui(obj, callback);
  }
</script>
";
 }

 ... code ...
 print_sharescript();
 foreach ($des=>$val) {
 $json = addslashes(json_encode($val));
      echo "<a onclick='postToFeed($json); return false;'>Share</a>";
 }
 .... code ....

Also look into adopting some templating system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM