如何将PHP放入Javascript中? [英] How can you put PHP inside a Javascript?

查看:110
本文介绍了如何将PHP放入Javascript中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过类似这样的PHP函数来检索Facebook页面的计数:

I am retrieving a Facebook Page Like count via a PHP function like this:

<?php
function fbLikeCount($id,$appid,$appsecret){
$json_url ='https://graph.facebook.com/'.$id.'?access_token='.$appid.'|'.$appsecret.'&fields=likes';
$json = file_get_contents($json_url);
$json_output = json_decode($json);
if($json_output->likes){
    return $likes = $json_output->likes;
}else{
    return 0;
}
}
?>

然后,我能够像这样毫无问题地回应这个问题:

Then, I am able to echo this out no problem like this:

<?php
echo number_format(fbLikeCount('companynamegoeshere','XXXXXXXXXXXX','XXXXXXXXXXX'));
?>

但是,我正在使用JavaScript函数来制作此动画,以显示页面上显示数字的位置,如下所示:

But, I am using a JavaScript function to do this animation for where teh number is displayed on the page, like this:

<script>
$({someValue: 0}).animate({someValue: 450700}, {
duration: 3000,
easing: 'swing',
step: function () {
   $('#facebookCount').text(commaSeparateNumber(Math.round(this.someValue)));
},
complete:function(){
      $('#facebookCount').text(commaSeparateNumber(Math.round(this.someValue)));
  }
});
</script>

JS代码中450700所在的位置是我需要输入PHP回显编号的位置.甚至有可能在JS中放入PHP回声(如果我先将其设置为变量?).

Where that 450700 is in the JS code is where I need to put the PHP echo'ed number. Is it even possible to put a PHP echo (if I make it a variable first?) into the JS.

我尝试了很多很多事情,撞到了砖墙.任何帮助,我们将不胜感激.

I've tried many, many things and hitting a brick wall. Any help is greatly appreciated.

谢谢!

推荐答案

要修改@Pedro Lobito的答案-您可以按以下方式在js中回显该值:

To modify @Pedro Lobito's answer - you echo the value inside the js as follows:

<?php
$number = "1234";
?>
<script>
$({someValue: 0}).animate({someValue: <?php echo"$number";?>}, {
duration: 3000,
...

或者:

    <?php
    $number = "1234";
    ?>


    <script>
    var testValue = <?php echo"$number";?>;
    $({someValue: 0}).animate({someValue: testValue}, {
    duration: 3000,
    ...

甚至

<input type="hidden" name="testInput" value="<?php echo"$number";?>" />

        <script>
        var testValue = $('[name=testInput]').val();
        $({someValue: 0}).animate({someValue: testValue}, {
        duration: 3000,
        ...

或隐藏的div/span-但将display:none移至外部CSS工作表

or a hidden div / span - but move the display:none to the external CSS sheet

<span style="display:none"  id="testSpan"><?php echo"$number";?></span>

        <script>
        var testValue = $('#testSpan').text();
        $({someValue: 0}).animate({someValue: testValue}, {
        duration: 3000,
        ...

这篇关于如何将PHP放入Javascript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆