简体   繁体   中英

how to get a data from a DB using MYSQL and store it in javascript Array

有没有可能使用MYSQL从数据库获取数据并将其存储在javascript Array中的方法?

<?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}

Then you can do something like

<script type="text/javsacript">
var abc = "<? echo json_encode($arr);?>";
</script>

OR

echo '<script type="text/javsacript">
        var abc ="'.json_encode($arr).'";
    </script>'; 

关联数组的形式获取它,然后使用json_encode创建一个存储在字符串中的JavaScript数组。

.

// 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>";

Actually this is a pretty vague question, but I think AJAX is what you're looking for.

EDIT: Of course JSON will workout too and might even be more straight forward...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM