如何将php变量从单独的文件调用到HTML文件中

时间:2014-01-20 23:24:58

标签: javascript php json

这是我要分离javascript的实际文件。 我怎么告诉javascript在哪里寻找php文件,目前我只能从php文件中执行javascript ..

<?php
date_default_timezone_set('Europe/London');
require_once("DbConnect.php");

$sql = "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`,
`picture` FROM historylist  ORDER BY `date_played` DESC LIMIT 5 ";

$result = $db->query($sql);

$lastplayed = array();
$i = 1;
while ($row=$result->fetch_object()) {
$lastplayed[$i]['artist'] = $row->artist;
$lastplayed[$i]['title'] = $row->title;
$lastplayed[$i]['label'] = $row->label;
$lastplayed[$i]['albumyear'] = $row->albumyear;
$lastplayed[$i]['date_played'] = $row->date_played;
$lastplayed[$i]['duration'] = $row->duration;
$lastplayed[$i]['picture'] = $row->picture;
$i++;
}

$starttime = strtotime($lastplayed[1]['date_played']);
$curtime = time();
$timeleft = $starttime+round($lastplayed[1]['duration']/1000)-$curtime;
$secsremain = (round($lastplayed[1]['duration'] / 1000)-($curtime-$starttime));


$lastplayedjson = json_encode( $lastplayed );
?>

我希望此部分位于单独的文件中

<script type="text/javascript">


var lastplayedjson = <?php echo $lastplayedjson ?>;


alert( lastplayedjson[1].title );
alert( lastplayedjson[2].title );
alert( lastplayedjson[3].title );
alert( lastplayedjson[4].title );
</script>

2 个答案:

答案 0 :(得分:0)

你可以include第一个php文件(我们称之为fileA.php),它允许fileB.php访问它的所有变量

档案A

<?php 
$cats = 'topkek';

文件B

<?php
include('/path/to/fileA.php');
echo $cats;

应输出

topkek

您可以在includerequireinclude_oncerequire_once

上看到here的差异

答案 1 :(得分:0)

在你的php中:

include_once('templates/template-name.php');