繁体   English   中英

结合Javascript HTML PHP

[英]to combine Javascript HTML PHP

我正在做这个小项目。 一切似乎都正常,但我想做得更好。 我有代码

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

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

-我的问题

如何将(组合)第2部分代码转换为php。 我尝试绕行回显,但未成功

我想将Part2分配为Php变量$ Graph1,然后在页面上回显$ graph1,因为它与我的其他代码更好地工作,因此它是一致的。

所以我想要这样的东西:

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

您为什么不只在?>之后添加它?>

在PHP中,您可以包含这样的HTML

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

您还可以将PHP包含到HTML中

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

您还可以将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