使用PHP和AJAX从MySQL表创建JS数组的最佳方法是什么?

时间:2012-10-18 20:37:26

标签: php javascript mysql

我认为这会更简单,但我在网上找到一个简单的答案时遇到了一些困难。

我只是想从带有ajax的MySQL表中获取数据 并将其转换为js数组。

我的桌子非常简单..它只是:

Table 1
 id     value
  1     1 
  2     2 
  3     3

这样做的最佳方式是什么?

到目前为止,我有php文件:

while($row = mysql_fetch_array($query)) {$array[] = $row;}

发出如下内容:

Array ( [0] => Array ( [0] => 7 [idGlobal] => 7 [1] => 4.9 [tc] => 4.9 ) ) Array ( [0]     => Array ( [0] => 7 [idGlobal] => 7 [1] => 4.9 [tc] => 4.9 ) [1] => Array ( [0] => 3     [idGlobal] => 3 [1] => 2.2 [tc] => 2.2 ) ) Array ( [0] => Array ( [0] => 7 [idGlobal] => 7 [1] => 4.9 [tc] => 4.9 ) [1] => Array ( [0] => 3 [idGlobal] => 3 [1] => 2.2 [tc] => 2.2 ) [2] => Array ( [0] => 5 [idGlobal] => 5 [1] => 1.9 [tc] => 1.9 ) ) Array ( [0] => Array ( [0] => 7 [idGlobal] => 7 [1] => 4.9 [tc] => 4.9 ) [1] => Array ( [0] => 3 [idGlobal] => 3 [1] => 2.2 [tc] => 2.2 ) [2] => Array ( [0] => 5 [idGlobal] => 5 [1] => 1.9 [tc] => 1.9 ) [3] => Array ( [0] => 6 [idGlobal] => 6 [1] => 1.9 [tc] => 1.9 ) ) Array ( [0] => Array ( [0] => 7 [idGlobal] => 7 [1] => 4.9 [tc] => 4.9 ) [1] => Array ( [0] => 3 [idGlobal] => 3 [1] => 2.2 [tc] => 2.2 ) [2] => Array ( [0] => 5 [idGlobal] => 5 [1] => 1.9 [tc] => 1.9 ) [3] => Array ( [0] => 6 [idGlobal] => 6 [1] => 1.9 [tc] => 1.9 ) [4] => Array ( [0] => 4 [idGlobal] => 4 [1] => 1.6 [tc] => 1.6 ) )

但我仍然不知道用ajax获取JS数组的最佳方法

3 个答案:

答案 0 :(得分:3)

$query = "SELECT id, value FROM table";
$data = array();

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}

header('Content-Type: application/json');
echo json_encode($data);

答案 1 :(得分:2)

  1. 从mysql查询
  2. 获取结果oas associative array
  3. json编码数组
  4. 将json字符串返回给javascript代码。

答案 2 :(得分:1)

使用php函数json_encode创建包含json的字符串。稍后在javascript中检索字符串时,最简单的方法是将其转换为类似这样的数组。

var myArray = eval('('+ jsonStringRetrieved +')');

并查看这些内容 how to use json_encode Safely turning a JSON string into an object