名站网址导航为大家免费提供关于网站编程方面的知识。
php将从数据库中获得的数据转换成json格式并输出
- 本篇文章的具体介绍如下请大家仔细看
<?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> |
关于网站编程方面的知识就说道这里了,希望能够对大家有作用。,PhP,中,生成,json,信息,的,方法,