如何将我的代码分离到不同的php文件?

时间:2015-04-10 15:16:24

标签: javascript php json flot

我有使用flot库绘制绘图的代码。绘图数据在我的本地数据库中。

在一个文件中有php,javascript和html代码。我怎样才能将php代码分离到不同的文件中,只留下html和javascript。

代码如下所示:

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src='js/flot/jquery.flot.min.js'></script>
    </head>
    <body>
    <div id="placeholder" style="width:600px;height:300px;"></div>
    <?php
    $server = "localhost";
    $user="root";
    $password="";  
    $database = "testing";
    $connection = mysqli_connect($server,$user,$password,$database);

    $query = "SELECT longLocation, latLocation FROM coords";
    $result = $connection->query($query);   

    while($row = mysqli_fetch_assoc($result))
    {
        $dataset1[] = array($row['longLocation'],$row['latLocation']);
    }

   ?>
   <script type="text/javascript">
    $(function () {
   var dataset1 = <?php echo json_encode($dataset1); ?>;
   $.plot("#placeholder", [ dataset1 ]);
   });
   </script>
   </body>
   </html>

1 个答案:

答案 0 :(得分:1)

如果你想摆脱文件中的所有php代码,你需要使用AJAX。你最终会得到2个文件,其中一个文件包含打印出json编码数据的html和PHP文件。

的index.html:

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script src='js/flot/jquery.flot.min.js'></script>
</head>
<body>
  <div id="placeholder" style="width:600px;height:300px;"></div>
  <script type="text/javascript">
    $(function () {
      $.getJSON('get_data.php', {}, function (data) {
        $.plot("#placeholder", [ data ]);
      });
    });
  </script>
</body>
</html>

get_data.php:

<?php
$server = "localhost";
$user="root";
$password="";  
$database = "testing";
$connection = mysqli_connect($server,$user,$password,$database);

$query = "SELECT longLocation, latLocation FROM coords";
$result = $connection->query($query);   

$dataset = [];

while($row = mysqli_fetch_assoc($result))
{
    $dataset[] = array($row['longLocation'],$row['latLocation']);
}

echo json_encode($dataset);