您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
自己模拟了一点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>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。