如何通过javascript函数返回php值

时间:2016-10-26 16:42:20

标签: javascript php jquery

我有一些PHP数据,比如$ total_post,$ categories,$ user来自db。

  

我想创建这样的功能..我不知道它是否正确或   不是..这就像我只是想..

var randomScalingFactor = function(){ 
  return "<?php  echo $total_post; ?>";
};

var barChartData = {
  labels : ["Active Posts","catagories", "User", "Comments","current online" ],
  datasets : [
    {
      fillColor : "rgba(48, 164, 255, 0.2)",
      strokeColor : "rgba(48, 164, 255, 0.8)",
      highlightFill : "rgba(48, 164, 255, 0.75)",
      highlightStroke : "rgba(48, 164, 255, 1)",
      data : [ randomScalingFactor() , 400, 300, 550,895]
    }
  ]
}

2 个答案:

答案 0 :(得分:0)

是的,它会起作用,在php编译页面之后你会有这个:

var randomScalingFactor = function(){ 
     return "total_post_value";
};

您也可以这样做:

var randomScalingFactor = "<?php  echo $total_post; ?>";

所以你不需要一个功能。但是当你的项目增长时,它可能会有点讨厌,所以我建议在站点中创建所需的前端参数列表,如下所示:

<head>
    <div id="back-end-parameters">
        <div id="total-post"><?php echo $total_post; ?></div>
    </div>
</head>
<footer>
   <script>
       var total_post = document.getElementById('total-post').innerHtml;
   </script>
</footer>

答案 1 :(得分:0)

它最后工作...... thx家伙试图帮助我

                var barChartData = {
                    labels : ["Active Posts","catagories", "User", "Comments","current online" ],
                    datasets : [
                        {
                            fillColor : "rgba(48, 164, 255, 0.2)",
                            strokeColor : "rgba(48, 164, 255, 0.8)",
                            highlightFill : "rgba(48, 164, 255, 0.75)",
                            highlightStroke : "rgba(48, 164, 255, 1)",
                            data : [<?php echo $postCount; ?>, <?php echo $categoryCount; ?>, <?php echo $userCount ;?>, <?php echo $commentCount; ?>, 2 ]
                        }
                    ]

                }

它甚至不需要声明变量..