从php获取json数据使用js读取显示到网页笔记
程序员文章站
2022-08-09 21:27:13
php代码
"hellojso...
php代码
<?php //json与数组转换 $array = array("username" => "hellojson","age" => 23,"sex"=>"M");//定义php数组 $res=json_encode($array); //var_dump($res); echo $res;//将结果输出到页面 ?> HTML代码 <html> <head> <title></title> <script src="jquery-1.11.0.min.js"></script> </head> <body> <script type="text/javascript"> $(function(){ $(document).on("click",'.test',function(){ var id=$(this).attr("id"); var data={id:id} //var aaa=[{"0":"1","id":"1","1":"hello","name":"hello","2":"","password":""},{"0":"2","id":"2","1" // :"world","name":"world","2":"","password":""},{"0":"3","id":"3","1":"helloworld","name":"helloworld" // ,"2":"","password":""}] // alert(aaa[2].name) $.ajax({ type:"GET", data:data, url:'xml.php', dataType:"json", success:function(msg){ if(msg){ var res=eval(msg);//在php中返回的数据如果不能直接使用可以转换一下,使用eval()函数可以实现转化。 //alert(res.username) alert(res[1].name)//弹出要取的数据 //console.log(res) } } }); }) }) </script> <p class="test" id="1"> <input type="button" value="button"> </p> <p class="getmsg"> </p> </body> </html>
在原生js中还可以使用JSON.parse()函数来转为json格式,在php中已经转化为json格式了可以直接获取
alert(msg[0].name)//msg为返回的json格式
上一篇: Storm是什么
下一篇: SVM基本概念及Python实现代码