<?php //php中生成json信息 //json_encode(數組/對象) $color = array('red','blue','green'); //【索引數組】 echo json_encode($color),"<br />"; //["red","blue","green"] $animal = array('east'=>'tiger','north'=>'wolf','south'=>'monkey'); //【關聯數組】 echo json_encode($animal),"<br />";//{"east":"tiger","north":"wolf","south":"monkey"} //【索引關聯數組】 $animal2 = array('east'=>'tiger','north'=>'wolf','duck','south'=>'monkey'); echo json_encode($animal2),"<br />";//{"east":"tiger","north":"wolf","0":"duck","south":"monkey"} //[{},{},{}] //{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"9","WD":"南風","WS":"2級","SD":"26%","WSE":"2","time":"10:20","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暫無實況","qy":"1014"}} //{名稱:[],名稱:[],名稱:[]} //【對象生成json信息】 class Person{ public $addr = "beijing"; public $height = 170; public function study(){ echo "study php"; } } $tom = new Person(); //只是對象的屬性給生成json信息 echo json_encode($tom);//{"addr":"beijing","height":170}
1.json
json_encode(數組/對象)------------>生成json信息,
json_decode(json信息); 反編碼json信息
對json字符串信息進行反編碼,變為當前語言可以識別的信息。
2. javascript接收處理json信息
通過eval()把接收的json字符串變成真實的對象信息
代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>新建網頁</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <script type="text/javascript"> function showweather(){ //利用ajax獲得天氣預報信息 //利用javascript+dom處理並顯示天氣信息 var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState==4){ //alert(xhr.responseText); console.log(typeof xhr.responseText);//string //要把接收的“字符串”變為“對象” //'{"addr":"\u5317\u4eac","temp":"9-22","wind":"north4-5"}' eval("var info="+xhr.responseText); var str = "地址:"+info.addr+";溫度:"+info.temp+";風向:"+info.wind; document.getElementById('result').innerHTML = str; } } xhr.open('get','./03.php'); xhr.send(null); } window.onload = function(){ showweather(); } // //s字符串變為對象obj // var s = "{name:'tom',height:170}"; // //"var obj="+"{name:'tom',height:170}"====>"var obj={name:'tom',height:170}" // //console.log("var obj="+s); // eval("var obj="+s); // console.log(obj);//Object { name="tom", height=170} </script> <style type="text/css"> </style> </head> <body> <h2>獲得天氣預報接口信息</h2> <div id="result"></div> </body> </html>