<?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>
<div class="test" id="1">
<input type="button" value="button">
</div>
<div class="getmsg">
</div>
</body>
</html>
在原生js中還可以使用JSON.parse()函數來轉為json格式,在php中已經轉化為json格式了可以直接獲取 alert(msg[0].name)//msg為返回的json格式