js mysql json字符串转数组中_php数据库数据转换为js中的json对象
/
1.在company數(shù)據(jù)user表中取出10條數(shù)據(jù),保存為數(shù)組
2.在將數(shù)組轉(zhuǎn)化為json格式,傳遞給js
3.用json解析器將傳遞過來(lái)的json字符串轉(zhuǎn)化為json對(duì)象,
4.用document.write輸出語(yǔ)句打印在頁(yè)面上
*/
$conn = mysql_connect(“l(fā)ocalhost”,”root”,”root”);???//連接數(shù)據(jù)庫(kù)
mysql_query(“set names utf8″);?? ??? ??? ??? ??? ????//設(shè)置編碼
mysql_select_db(“company”,$conn);?? ??? ??? ??? ??? ?//選擇庫(kù)
$sql = “select * from user limit 10″;?? ??? ??? ??? ?//在user表中查詢10條數(shù)據(jù)
$res = mysql_query($sql);?? ??? ??? ??? ??? ??? ??? ?//執(zhí)行sql語(yǔ)句
$arr = array();
while($row = mysql_fetch_array($res,MYSQL_ASSOC)){???//查詢出來(lái)sql
$arr[] = $row;?? ??? ??? ??? ??? ??? ??? ??? ????//將查詢出來(lái)的結(jié)果賦給數(shù)組$arr
}
$str = json_encode($arr);?? ??? ??? ??? ??? ??? ????//將數(shù)組轉(zhuǎn)化為json格式的字符串
?>
var jsonString = ‘<?php echo $str;?>’;?? ??? ??//傳遞php中的數(shù)據(jù)給js
//document.write(jsonString);
var jsonObject = json_parse(jsonString);?? ??? ??? ?//將json字符串轉(zhuǎn)化為js中的json對(duì)象
for(var i = 0; i < jsonObject.length; i++){?? ??? ??? ?//for循環(huán)打印
document.write(“
”);document.write(“
”,jsonObject[i].uid,””);document.write(“
”,jsonObject[i].username,””);document.write(“
”,jsonObject[i].sex,””);document.write(“
”,jsonObject[i].email,””);document.write(“
”);}
總結(jié)
以上是生活随笔為你收集整理的js mysql json字符串转数组中_php数据库数据转换为js中的json对象的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php 输出数组函数调用函数,php
- 下一篇: 信息学奥赛一本通 1309:【例1.6】