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>

  

猜你喜欢

转载自www.cnblogs.com/Im-Victor/p/9246853.html