失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > js mysql json字符串转数组中_php数据库数据转换为js中的json对象

js mysql json字符串转数组中_php数据库数据转换为js中的json对象

时间:2021-11-18 20:47:03

相关推荐

js mysql json字符串转数组中_php数据库数据转换为js中的json对象

/

1.在company数据user表中取出10条数据,保存为数组

2.在将数组转化为json格式,传递给js

3.用json解析器将传递过来的json字符串转化为json对象,

4.用document.write输出语句打印在页面上

*/

$conn = mysql_connect(“localhost”,”root”,”root”);//连接数据库

mysql_query(“set names utf8″);//设置编码

mysql_select_db(“company”,$conn);//选择库

$sql = “select * from user limit 10″; //在user表中查询10条数据

$res = mysql_query($sql); //执行sql语句

$arr = array();

while($row = mysql_fetch_array($res,MYSQL_ASSOC)){//查询出来sql

$arr[] = $row; //将查询出来的结果赋给数组$arr

}

$str = json_encode($arr);//将数组转化为json格式的字符串

?>

var jsonString = ‘<?php echo $str;?>’; //传递php中的数据给js

//document.write(jsonString);

var jsonObject = json_parse(jsonString); //将json字符串转化为js中的json对象

for(var i = 0; i < jsonObject.length; i++){ //for循环打印

document.write(“

”);

document.write(“

”,jsonObject[i].uid,””);

document.write(“

”,jsonObject[i].username,””);

document.write(“

”,jsonObject[i].sex,””);

document.write(“

”,jsonObject[i].email,””);

document.write(“

”);

}

如果觉得《js mysql json字符串转数组中_php数据库数据转换为js中的json对象》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。