How to properly populate javascript objects from global variables

时间:2015-07-28 16:24:00

标签: javascript php html

I started playing with the Instagram API. The following code snippet retrieves the Instagram ID of a username.

<?php 
    $username = "[SOME-USERNAME]";
    $client_id = "[CLIENT-ID]";
    $access_token = "[ACCESS-TOKEN]";
    $json_url = "https://api.instagram.com/v1/users/search?q=".$username."&client_id=".$client_id;
    $json = file_get_contents($json_url);
    $links = json_decode($json);

    echo $links->data[0]->username."'s Instagram ID : ".$links->data[0]->id."\n";
?>

Then I want to use that ID to generate the user's Instagram album via Instafeed.js.

<script type="text/javascript">
    var user_id = "<?php echo $links->data[0]->id; ?>";
    var access = "<?php echo $access_token; ?>";

    var userFeed = new Instafeed({
        get: 'user',
        //userId: 0,
        //accessToken: ' ',
        links: true,
        resolution: 'standard_resolution'
    });
    userFeed["userId"] = user_id;
    userFeed["accessToken"] = access;
    userFeed.run();
</script>

The problem is the function run() doesn't seem to work when I populate the object from global variables.

2 个答案:

答案 0 :(得分:1)

What you want to do is build your JSON object that you are passing into the Instafeed object using the variables you get from PHP

<script type="text/javascript">
    var userFeed = new Instafeed({
        get: 'user',
        userId: <?= json_encode($links->data[0]->id) ?>,
        accessToken: <?= json_encode($access_token) ?>,
        links: true,
        resolution: 'standard_resolution'
    });
    userFeed["userId"] = user_id;
    userFeed["accessToken"] = access;
    userFeed.run();
</script> 

答案 1 :(得分:1)

After reviewing a little bit the library code, the way that you set the userId and other options is not correct. Properties should be set inside options object.

Use:

userFeed.options.userId = user_id;
userFeed.options.accessToken = access;
userFeed.run();

Instead of:

userFeed["userId"] = user_id;
userFeed["accessToken"] = access;
userFeed.run();