如何正确地从全局变量填充javascript对象


How to properly populate javascript objects from global variables

我开始使用Instagram API。下面的代码片段检索用户名的Instagram ID。

<?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";
?>

然后我想使用该ID通过Instafeed.js生成用户的Instagram相册。

<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>

问题是当我从全局变量填充对象时,函数run()似乎不起作用。

在稍微检查了库代码之后,您设置userId和其他选项的方式是不正确的。属性应该在options对象内设置。

使用:

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

代替:

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

你要做的是建立你的JSON对象,你要传递到Instafeed对象使用从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>