有没有办法使用MYSQL从数据库获取数据并将其存储在javascript数组中?
答案 0 :(得分:1)
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
// of course this array can be created by looping through your mysql result set
// and doing a mysql_fetch_assoc
// for example, $sql = your query here
// mysql_fetch_assoc($result); etc
echo json_encode($arr);
?>
{"a":1,"b":2,"c":3,"d":4,"e":5}
然后你可以做类似
的事情<script type="text/javsacript">
var abc = "<? echo json_encode($arr);?>";
</script>
OR
echo '<script type="text/javsacript">
var abc ="'.json_encode($arr).'";
</script>';
答案 1 :(得分:1)
将其作为associative array获取,然后使用json_encode创建一个存储在字符串中的JavaScript数组。
答案 2 :(得分:1)
// first, build your query:
$sql = "SELECT name, email FROM users";
$result = mysql_query($sql);
// then build up your data
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
//then write it in a way Javascript can understand:
echo "<script type=\"text/javascript\">\n"
. "var users = " . json_encode($rows) . ";\n"
. "</script>";
答案 3 :(得分:0)
实际上这是一个非常含糊的问题,但我认为AJAX正是你所期待的 对于。
编辑:当然JSON也会锻炼,甚至可能更直接......