-1

I thought this would be much simpler but I'm having some difficulty finding a simple answer online.

I simply want to get data from an MySQL table with ajax and transform it into a js array.

My table is ultra simple.. it's just:

Table 1
 id     value
  1     1 
  2     2 
  3     3

What is the best way to do this?

So far I have the php file:

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

which emits something like:

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

but I still don't know the best way to get it with ajax to a JS array

4

3 回答 3

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);
于 2012-10-18T20:41:25.943 回答
2
  1. 从 mysql 查询
  2. 获取结果 oas 关联数组
  3. json对数组进行编码
  4. 将 json 字符串返回到 javascript 代码。
于 2012-10-18T20:40:26.347 回答
1

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

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

并查看这些 如何使用 json_encode 安全地将 JSON 字符串转换为对象

于 2012-10-18T20:43:53.397 回答