2012-03-19 63 views
0

我认为这是一个我不知道的JavaScript的情况,但我不能为上帝的爱得到这个工作如何在JavaScript中使用PHP变量?

由于某种原因,创建增值税取消了我的java警报代码。 (也许BC错了) 而我的java变量没有被正确设置。

我指出了我的意见

在我的SQL的问题,我有温度所有关联值盘“身份证”。 所以在这我的数据结构是:

$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"; 

MY尝试(错误的代码): //我简化了这个代码了。在我自己的版本中,只能加入作品,当我用一个实际的指数“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> 
+3

Java!= JavaScript ...你可以发布生成的HTML吗?另外,你不能像这样混合使用JavaScript/PHP。 – 2012-03-19 20:51:01

回答

4

你不能混用PHP和JavaScript那样的。 JavaScript中的变量不在PHP中分析。
即使将index替换为变量$index100,您的代码仍会错过引号。

请改用以下:

<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;后。否则,可以生成一个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 
+0

谢谢!我现在明白过程是如何运作的。当我尝试使用json_encode时,程序停在那条线上。 var array = <?php echo json_encode($ phparray); ?>; 显示为 var array = 我的程序停止。任何想法为什么? – CREW 2012-03-19 21:50:43

+0

@CREW发生错误了吗? – 2012-03-19 22:00:54

1

看在客户端浏览器生成的代码,你会发现它看起来像这样:

var joined = [First Element - Sub2, Second Element etc.....] 

注意缺少你插入字符串的引号。您已经创建了Javascript语法错误,这会导致嵌入这些变量的整个<script>块被终止。

正如Rob W上面提到的那样,您必须使用json_encode()来生成任意文本中的VALID JavaScript。作为一般规则,如果你已经让PHP生成了任何javascript,并且特别是在填充这样的变量时,使用json_encode() - 它会使这些头痛不已。

1

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