问题
I am trying to call a php code which retrieves data from mysql table and populate it to an array and accessing it in the javascript. But screen shows nothing I know for sure there is no problem with php in populating the data, and referencing the php variable in javascript I have included the file and the file is in my Eclipse (juno) project only. But still why I get this problem?
Any suggestions please?
sample.jsp:
<div id="placeholder" style="width:600px;height:300px;"></div>
<script type="text/javascript" >
$(function () {
include("db.php");
var dataset1 = "<?php echo json_encode($dataset1); ?>";
$.plot($("#placeholder"), [ dataset1 ]);
});
db.php:
<?php header('Content-type: text/javascript');
$server = "localhost";
$user="harish";
$password="password";
$database = "db";
$connection = mysql_connect($server,$user,$password);
$db = mysql_select_db($database,$connection);
$query = "SELECT xval,yval FROM flottable";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$dataset1[] = array($row['xval'],$row['yval']);
}
?>
Reference: http://www.javascriptkit.com/javatutors/externalphp.shtml
I also googled and found out that if I add this to an .htaccess
file it would work. I tried this as well but nothing works.
Any idea what the problem is?
AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js
<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>
回答1:
Seems you forgot to set include("db.php"); between php opening brackets.
<?php include("db.php");?>
should do the trick
回答2:
Your include()
command should be in <?php ... ?>
tags, and with json_encode
you don't need quotes around it (in fact using quotes will severely break your JavaScript). Correct these two errors and your code should work.
来源:https://stackoverflow.com/questions/13215286/referencing-php-in-javascript