-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. Fetch Result 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 に答える