简体   繁体   English

结合Javascript HTML PHP

[英]to combine Javascript HTML PHP

I am doing this little project. 我正在做这个小项目。 Everything seems working , but I want to make even better. 一切似乎都正常,但我想做得更好。 I have code 我有代码

-Part1 -takes date from database and converts to JSON -Part1-从数据库获取日期并转换为JSON

<?php
$sth = mysql_query("select Value, Stats from table");
$rows = array();
$flag = true;
$table = array();
$table['cols'] = array(
array('label' => 'Stats', 'type' => 'string'),
array('label' => 'Value', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
$temp[] = array('v' => (string) $r['Stats']); 
$temp[] = array('v' => (int) $r['Value']); 
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table, JSON_NUMERIC_CHECK);
?>  

-Part 2 Draws Google Bar chart and shows it on page -第2部分绘制Google条形图并将其显示在页面上

<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);   
   var options = {
    legend: {position: 'none'},
           bar: {groupWidth: "85%"},
           colors:['#4A9218'],
    hAxis: {viewWindowMode: 'explicit'},
  }                        };                  
  var chart = new google.visualization.BarChart(document.getElementById('charts_div'));
  chart.draw(data, options);
}
</script>
<div class='data' id="charts_div" style="width:100%; height:200px"></div>

-My Qyestion -我的问题

How to convert (combine) Part2 code to php. 如何将(组合)第2部分代码转换为php。 I tried echo around lines, but unsuccesfully 我尝试绕行回显,但未成功

I want to assign Part2 as Php variable $Graph1 and then echo $graph1 on page, because It works better with my other code, so its consistent. 我想将Part2分配为Php变量$ Graph1,然后在页面上回显$ graph1,因为它与我的其他代码更好地工作,因此它是一致的。

So I would like something like: 所以我想要这样的东西:

<?php
Part1
?>
<?php
$graph1=."<script>...</script>"
$graph = "<div class='data'><ul>" . $graph1 . "</ul></div>
echo $graph
?> 

Why don't you just add it after the ?> ? 您为什么不只在?>之后添加它?>

In PHP you can include HTML like this 在PHP中,您可以包含这样的HTML

<?php
// My PHP Code
echo "test";
?>
<H1>My Title in HTML</H1>
<script> ... </script>
<?php
echo "test2";
?>

You can also include PHP into HTML 您还可以将PHP包含到HTML中

<script> var a = "<?php echo $somevariable; ?>"</script>

You can also wrap your HTML code into a PHP variable care about the " . You will need to escape it or us single quote instead: 您还可以将HTML代码包装到关心"的PHP变量中。您需要对其进行转义或使用单引号引起来:

<?php
$myHTML = "<script> window.location=\"mylocation.com\";</script>";
$myHTML = "<script> window.location= 'mylocation.com' ;</script>";
...
echo $myHTML;
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM