[英]How can I use a PHP variable inside of my JavaScript?
我認為這是我不懂JavaScript的一種情況,但是我不能為上帝的愛而努力
由於某種原因,創建vars會取消我的Java警報代碼。 (也許是因為它錯了)而且我的Java變量沒有正確設置。
我在評論中指出了問題
在我的SQL中,我的Temperatures都帶有關聯值磁盤“ id”。 所以我的數據結構是:
$array[id];
$array[id]=array();
//For every new element
//Using while ($row = mysql_fetch_assoc($result))
$array[id][]="temperature";
//second id
$array[id2];
$array[id2]=array();
//For every new element
$array[id2][]="temperature";
$array[id2][]="temperature2";
$array[id2][]="temperature3";
$array[id2][]="temperature4";
我的嘗試(錯誤代碼)://我簡化了此代碼。 在我自己的版本中,僅當我使用實際索引“ 174”而不是javascript變量174時,聯接才起作用。在此簡化版本中,無法獲取聯接以得到警告
<?php
$phparray=array();
$phparray["100"]="First Element";
$phparray["101"]="Second Element";
$phparray["102"]="Third Element";
$phparray["100"]=array();
$phparray["101"]=array();
$phparray["100"][]="First Element - Sub 2";
$phparray["100"][]="First Element - Sub 3";
$phparray["101"][]="Second Element - Sub 2";
echo $phparray["100"]; //Does not show 'First Element'. Shows Array
echo $phparray["100"][0]; //Correctly shows sub element
//var_dump($phparray);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Associative Array in PHP used in Java Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
var index=100;
//var index2=<?php echo $phparray[index]; ?>; //Supposed to output 'First Element'
var joined=[<?php echo join($phparray[index], ', '); ?>]; //Supposed to join elements of '100'
alert("hello"); //This line does not work anymore after the var index2 made above
</script>
</head>
<body>
<div id="container" style="height: 500px; min-width: 600px"></div>
</body>
</html>
編輯:這是我的php頁面的完整代碼:
<?php
include_once("../../config.php");
$conn=mysql_connect($dbhost,$dbuser,$dbpasswd) or die ('Error connecting to mysql');
mysql_select_db($dbname);
ini_set('error_reporting', E_ALL);
//ini_set('display_errors',1);
ini_set('log_errors',1);
$sql = "select disk_id from disk";
$result = mysql_query($sql);
$ids = array();
$names=array();
$temperatures = array();
while ($row = mysql_fetch_assoc($result)) {
$ids[] = $row['disk_id'];
$temperatures[]=$row['disk_id'];
//echo "<br>".$row['disk_id'];
}
//
foreach ($ids as $value)
{
//echo "--START ".$value."--<br>";
$sql = "select * from disk_data WHERE disk_id=".$value;
$result = mysql_query($sql);
$dates=array();
$key = array_search($value, $temperatures);
$temperatures[$value] = array();
//var_dump($temperatures);
while ($row = mysql_fetch_assoc($result))
{
$temps = $row['Temperature'];
$temp = explode("||", $temps);
$prehex=$temp[3];
$posthex=hexdec(substr($prehex,-2));
$predate=$row['create_date'];
$postdate =strtotime($predate)*1000;
$output="[".$postdate.", ".$posthex."]";
//$temperatures[$key][] = $output;
$temperatures[$value][] = $output;
$dates[]=$row['create_date'];
//echo $row['create_date']." ".end($temperatures[$key])."<br>";
}
}
print_r(array_keys($array));
var_dump($temperatures);
foreach ($ids as $value)
{
//echo $value;
$key = array_search($value, $temperatures);
//echo "Key: $key; Value: $temperatures[$value]<br />\n";
$comma = join($temperatures[$value],", ");
echo $comma;
echo "\n";
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var seriesOptions = [],
yAxisOptions = [],
seriesCounter = 0,
//names=[<?php echo join($ids, ', '); ?>],
names=["174"], //Above code works. BUT only using ID 174 to test
values=[<?php echo join($temperatures["174"], ', '); ?>], //Supposed to be ALL data. But temp 174
colors = Highcharts.getOptions().colors;
//alert(values);
$.each(names, function(i, name2) {
//alert(seriesOptions.length);
alert(name2.toString()); //Works....
var values=[<?php
echo join($temperatures[name2], ', '); ?>]; //Doesnt work
//alert(values);
console.log(values);
//document.write(values);
seriesOptions[i] =
{
name: name2,
data:values
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter++;
if (seriesCounter == names.length)
{
createChart();
}
});
// create the chart when all data is loaded
function createChart() {
chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
selected: 0
},
title: {
text: 'Test Performance Data',
style: {
margin: '10px 100px 0 0' // center it
}
},
yAxis: {
title: {text:'Temperature (°C)'},
labels: {
formatter: function() {
return this.value + '';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
line: {
gapSize: 0
},
series: {
//compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
yDecimals: 2
},
series: seriesOptions
});
}
});
</script>
</head>
<body>
<script type="text/javascript" src="../js/highstock.js"></script>
<script type="text/javascript" src="../js/themes/gray.js"></script>
<div id="container" style="height: 500px; min-width: 600px"></div>
</body>
</html>
您不能像這樣混合使用PHP和JavaScript。 JavaScript變量未在PHP中解析。
即使將index
替換為變量$index
或100
,您的代碼仍會丟失引號。
請改用以下內容:
<script type="text/javascript">
var index=100;
var array = <?php echo json_encode($phparray); ?>;
var joined = array[index];
最后一行輸出以下內容:
var joined={"100":["First Element - Sub 2","First Element - Sub 3"],"101":["Second Element - Sub 2"],"102":"Third Element"};
在嘗試此操作之前,請確保在var index = 100;
之后的行中刪除無效的注釋var index = 100;
。 否則,可能會生成PHP警告,從而使代碼無效:
var index=100;
//var index2=PHP Notice: Use of undefined constant index - assumed 'index' in /tmp/t.php on line 29
PHP Notice: Undefined index: index in /tmp/t.php on line 29
在客戶端瀏覽器中查看生成的代碼,您會發現它看起來像這樣:
var joined = [First Element - Sub2, Second Element etc.....]
請注意插入的字符串周圍沒有引號。 您已經創建了Javascript語法錯誤,該錯誤會殺死將這些變量嵌入其中的整個<script>
塊。
如Rob W所述,您必須使用json_encode()從任意文本中生成有效的JavaScript。
通常,如果您讓PHP生成任何javascript,尤其是在填充此類變量時,請使用json_encode()-這樣可以避免此類麻煩。
PHP在服務器端運行,並將其內容輸出到網頁中,然后再在瀏覽器中呈現並運行JavaScript。 (這意味着當php運行時,它不知道什么是“索引”,因為就其而言,它從未被定義。
我希望您想要做的是將PHP移至javascript中,以便隨后可以按頁面中的需要對其進行訪問。 在您的JavaScript中,只需添加以下內容即可:
var my_array_in_js = <?php echo json_encode($phparray); ?>;
這將導致PHP將其數組打印為json,然后可以根據需要通過javascript進行讀取。 然后要讀取特定的索引,只需使用
alert(my_array_in_js[index]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.