将变量从Php传递给js?

时间:2016-12-01 10:54:42

标签: javascript php wordpress-theming

class UserRepository { 

    // STEP 1
    public constructor(
        @inject("Provider<DbClient>") private provider: Provider<DbClient>
    ) {}

    public async getUser(): Promise<Users[]>{
        // STEP 2: (No initialization method is required)
        let db = await this.provider.someFancyNameForProvideValue;
        return db.collections.user.get({});
    }
}

locate必须包含php传递的每个tym代码循环的位置值,但为什么它实际上没有传递任何数据?

I am trying to send MY location to my js file. The location have the gives correct value when it is echoed from php. But when i try to access it from my js  it does not access the correct value instead contains the value `<?php echo $location;?>` well how can i access the value in js?

PHP
while($loop->have_posts()):$loop->the_post();?>
                    <?php $location=get_field('location');?>
                        <div class="col-sm-15">
                            <div class="widget-box">
                                <div class="weather"></div>
                            </div>
                        </div>
                    <?php
                endwhile;

2 个答案:

答案 0 :(得分:2)

问题是你是以.js格式保存整个文件,你写的php代码没有被解析。

相反,你可以这样做,只需在.php文件中设置变量,就像

一样。

PHP文件

window.locate="<?php echo $location?;>";

现在在js文件中使用该变量

alert (window.locate);

答案 1 :(得分:2)

从js文件中,无法访问php变量。

您可以从php文件执行此操作并访问js文件中的locate

<script>
    var locate = <?php echo $location ?>;
</script>