自己模擬了一點(diǎn)json數(shù)據(jù)存放在了數(shù)據(jù)庫(kù)一個(gè)表中大家可以自己模擬
{"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執(zhí)行的php文件
<?php $db = 'mysql'; $host ='localhost'; $port = '3306'; $dbname = 't_shop'; $user = 'root'; $pwd = ''; $dsn = "$db:host=$host;port=$port;dbname=$dbname"; //設(shè)定字符集 $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是一個(gè)含有json字段鍵值得二維數(shù)組 //打印結(jié)果 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"}} ) ) //定義一個(gè)空數(shù)組 把二維組里json解析后放進(jìn)新數(shù)組中 $json = array(); foreach ($row as $k=>$v){ //json新數(shù)組中放入我需要的id 和 json 的二維數(shù)組鍵 $json[$k]['id'] =$v['id']; //把鍵值為json的json串轉(zhuǎn)換成數(shù)組 放到新數(shù)組中 $json[$k]['json'] =json_decode($v['json'],true); //轉(zhuǎn)換成數(shù)組的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); //定義一個(gè)數(shù)組用來(lái)接受key // values.push(obj[key]);//取得value //追加內(nèi)容定義追加對(duì)象的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="點(diǎn)擊" onclick="get_wd()"/> </body>
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。