【问题标题】:Embed PHP into javascript with Ajax in order to store MySQL data in javascript objects使用 Ajax 将 PHP 嵌入到 javascript 中,以便将 MySQL 数据存储在 javascript 对象中
【发布时间】:2016-08-20 14:38:37
【问题描述】:

搜索这个问题的解决方案已经有一段时间了,似乎很多人都在问同样的问题。不过还没有找到一个好的答案。

我想做什么: 我有一个名为“fruitStand”的简单数据库。它有一个名为“fruitTable”的表,其中包含两列:

**fruit**   **cost**
  apple        5
  pear         4
 banana        2
 orange        6

我可以使用 PHP 脚本轻松获取行并将结果直接显示在屏幕上。但是,我希望能够将结果放入我的 javascript 数组中,以便我可以基于它构建一些图表。

在考虑this post 之后,我决定使用Jquery Ajax 将HTML/javascript 代码与PHP 代码粘合起来。我正在使用下面的两个文件(index.html 和 getData.php)以及数据库。当我点击“获取数据!”时,这会生成以下 HTML 输出。按钮:

apple5pear4banana2orange6

现在回到实际问题: 如何修改代码以便能够以 js 数组/对象形式返回结果?我希望它看起来像这样:

array1 = ["apple", "pear", "banana", "orange"]
array2 = [5,4,2,6]

最终目标是在绘制交互式图表时使用这些数组(稍后将添加按钮来选择水果/成本)。

index.html 文件:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {
   $("#display").click(function() {
     $.ajax({
       type: "GET",
       url: "getData.php",
       dataType: "html",
       success: function(response){
           var store = $("#responsecontainer").html(response);
       }
     });
   });
 });
</script>

<body>
<table border="1" align="center">
   <tr>
       <td> <input type="button" id="display" value="Get data!" /> </td>
   </tr>
</table>
<div id="responsecontainer" align="center"></div>
</body>
</html>

PHP 文件:

<?php
mysql_select_db('fruitStand',$con);
$result=mysql_query("select * from fruitTable",$con);

$con=mysql_connect("localhost","root","password");
if (!$con){
    die('Could not connect: ' . mysql_error());
}

while($data = mysql_fetch_row($result)){
    echo "$data[0]";
}
?>

【问题讨论】:

  • 你有没有想过使用 Ajax 来代替?直接通过 PHP 获取数据会使嵌入式脚本的大小变大,从而增加带宽使用和加载时间。将 Ajax 请求运行到返回 JSON 值的一端会更容易,然后您可以使用 Ajax 回调来处理它。
  • 好点。是的,我从今天开始,现在正试图让这个例子(Nehas 回复)工作:stackoverflow.com/questions/16707648/…

标签: javascript php mysql arrays


【解决方案1】:

这应该可以帮助您入门。循环遍历 PHP NOT JAVASCRIPT。

<script>
    <?php

        $i = 0;
        while($row = mysql_fetch_array($result)){
            echo "fruit[$i] = '" . $row['fruit'] . "';";
            echo "cost[$i] = '" . $row['cost'] . "';";
            $i++;
        }
    ?>
    </script>

【讨论】:

  • 感谢您的回复。我之前确实设法做到了这一点。棘手的部分是将结果放入 js 数组中,以便在绘制例如饼图时使用它们(需要 js 数组作为输入)。有什么建议我该怎么做?
  • 如果您将代码包装在像我的更新这样的脚本标签中,是否有错误? echo 应该回显 js 数组。
  • 我得到了 echo 打印输出,但我似乎没有得到 js 数组。
  • 请用准确的输出更新您的帖子,谢谢
【解决方案2】:

如果我想将一组数据从 php 共享到 Javascript,我会使用 JSON。

格式化你希望它在php中使用的数组,然后使用json_encode php方法将php数组转换为JSON。

在js中,使用JSON.parse将JSON解码为Javascript对象。

<html>
<head>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<body>
<?php $phpArray = array(); ?>
<?php $phpArray = array(array('fruit' => 'green', 'cost' => 10), array('fruit' => 'blue', 'cost' => 9),array('fruit' => 'red', 'cost' => 8), array('fruit' => 'yello', 'cost' => 7));?>



<script>
    var fruit = [];
    var cost = [];

    var jsString = '<?php echo json_encode($phpArray);?>';
    var jsArray = JSON.parse(jsString);
    for(var i in jsArray){
        fruit[i] = jsArray[i]['fruit'];
        cost[i] = jsArray[i]['cost'];
    }
    console.log(fruit);
    console.log(cost);
</script>

预期的控制台输出:

["green", "blue", "red", "yello"]
[10, 9, 8, 7]

【讨论】:

猜你喜欢
  • 2019-03-09
  • 1970-01-01
  • 2012-07-31
  • 2014-06-30
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 2021-06-08
  • 2020-12-06
相关资源
最近更新 更多