Home > Backend Development > PHP Tutorial > Get json data from php and use js to read and display it into web notes_PHP tutorial

Get json data from php and use js to read and display it into web notes_PHP tutorial

WBOY
Release: 2016-07-12 09:03:41
Original
1025 people have browsed it

Get json data from php and use js to read and display it to web notes

php code
<?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",&#39;.test&#39;,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:&#39;xml.php&#39;,
dataType:"json",
success:function(msg){
if(msg){
var res=eval(msg);//在php中返回的数据如果不能直接使用可以转换一下,使用eval()函数可以实现转化。
//alert(res.username)
alert(res[1].name)//弹出要取的数据
            //console.log(res)
       }
}
});

})
})
</script>
<div class="test" id="1">
<input type="button" value="button">
</div>
<div class="getmsg">

</div>
</body>
</html>
Copy after login

In native js, you can also use the JSON.parse() function to convert to json format. In php, it has been converted to json format and can be obtained directly
alert(msg[0].name)//msg is the returned json format

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1079752.htmlTechArticleGet json data from php and use js to read and display it to the web page notes php code?php//json and array conversion $ array = array(username = hellojson,age = 23,sex=M);//Define php array $res=json_encode(...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template