关于ajax读取数据表中存放复合json的问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于ajax读取数据表中存放复合json的问题相关的知识,希望对你有一定的参考价值。
自己模拟了一点json数据存放在了数据库一个表中大家可以自己模拟
{"1":{"id":"1","name":"asd","type":"1","value":"1L,4L"}} {"2":{"id":"2","name":"kjf","type":"1","value":"1L,4L"}} {"3":{"id":"3","name":"sss","type":"1","value":"1L,4L"}}
下面我用的pdo执行的php文件
<?php $db = ‘mysql‘; $host =‘localhost‘; $port = ‘3306‘; $dbname = ‘t_shop‘; $user = ‘root‘; $pwd = ‘‘; $dsn = "$db:host=$host;port=$port;dbname=$dbname"; //设定字符集 $options = array(PDO::MYSQL_ATTR_INIT_COMMAND=>‘SET NAMES \‘UTF8\‘‘); $pdo = new PDO($dsn,$user,$pwd,$options); $sql="select id,json from ecs_json"; $res=$pdo->query($sql); $row = $res->fetchAll(); // $row是一个含有json字段键值得二维数组 //打印结果 Array ( [0] => Array ( [id] => 1 [0] => 1 [json] => {"1":{"id":"1","name":"asd","type":"1","value":"1L,4L"}} [1] => {"1":{"id":"1","name":"asd","type":"1","value":"1L,4L"}} ) [1] => Array ( [id] => 2 [0] => 2 [json] => {"2":{"id":"2","name":"kjf","type":"1","value":"1L,4L"}} [1] => {"2":{"id":"2","name":"kjf","type":"1","value":"1L,4L"}} ) [2] => Array ( [id] => 3 [0] => 3 [json] => {"3":{"id":"3","name":"sss","type":"1","value":"1L,4L"}} [1] => {"3":{"id":"3","name":"sss","type":"1","value":"1L,4L"}} ) ) //定义一个空数组 把二维组里json解析后放进新数组中 $json = array(); foreach ($row as $k=>$v){ //json新数组中放入我需要的id 和 json 的二维数组键 $json[$k][‘id‘] =$v[‘id‘]; //把键值为json的json串转换成数组 放到新数组中 $json[$k][‘json‘] =json_decode($v[‘json‘],true); //转换成数组的json串 //Array ( [3] => Array ( [id] => 3 [name] => sss [type] => 1 [value] => 1L,4L ) ) } echo json_encode($json); exit;
前端ajax接收输出
<script> //解析json function Object(value){ return eval("("+value+")"); } function get_wd(){ $.get(‘./json.php‘,function (data){ var data = Object(data) for(i in data){ var obj = data[i][‘json‘]; var keys = []; var values = []; for(var key in obj){ // console.log(key); // keys.push(key); //定义一个数组用来接受key // values.push(obj[key]);//取得value //追加内容定义追加对象的id $(‘#div1‘).append(‘<p>‘+obj[key][‘name‘]+‘<p>‘); } } }) } </script> <title>前端接收json</title> </head> <body id="userlogin_body"> <div class="popped_card_con" id="div1"> <p>姓名</p> </div> <input type="button" value="点击" onclick="get_wd()"/> </body>
本文出自 “kangjunfei” 博客,转载请与作者联系!
以上是关于关于ajax读取数据表中存放复合json的问题的主要内容,如果未能解决你的问题,请参考以下文章
jQuery ajax 调用无法从 CakePHP 3.8 读取 json 编码数据(获取一个空数组)
ssm框架 怎么用ajax查询从数据库读取数据 返回json格式
关于Flash ActionScript3.0加载json数据问题