js调用php返回的json格式数据

php

2010-08-07 09:48

服务端

<?php

$arr = array(
array(
'name' => 'maarten',
'nick' => '海阔天空',
'contact' => array(
'email' => 'maarten@126.com',
'website' => 'http://www.mayongtao.com',
)),

array(
'name'=>'海格',
'nick'=>'haige',
'email'=>'haige@126.com',
'contact' => array(
'email' => 'haige@126.com',
'website' => 'http://www.haige.com',
))

);

$json_string = json_encode($arr);
//$obj = json_decode($json_string);
echo $json_string;
?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" charset="utf-8"/>
<script src="/js/jquery.js"></script>
<script>
$(document).ready(function(){
var url='http://localhost/4/json.php';
$('#startajax').click(function(){

$.post(url,'',function(msg){


var myObject = eval('(' + msg + ')'); //关键的一步,msg 为返回的类型为字符串,转化为json 对象 比较危险的对象

var str='';
var len=myObject.length;
for(i=0;i<len;i++){
str+='<tr><td>'+myObject[i].name+'</td><td>'+myObject[i].nick+'</td><td>'+myObject[i].contact.email+'</td><td></td><td>'+myObject[i].contact.website+'</td></tr>';
}

$('#rstable').html(str);


})


})


})
</script>
</head>
<body>
<input type="button" value="ajax 发起请求" id="startajax">
<div id="result">
<table id="rstable">

</table>

</div>
</body>
</html>

--------------------------------------------------------------------------------------------------------

2.php

//print_r($_GET);

$arr=array();

$arr['name']='china';

$arr['zip']='10050';

$arr['addr']='xxxx  china   设定的  ';

$json_string = json_encode($arr);

echo $json_string;


$.getJSON("2.php", { name: "John", time: "2pm" }, function(json){   //发送过去get提交 并传递2个值

     alert(json.name);

     alert(json.zip);

     alert(json.addr);

}); 

--------------------------------------------------------------------------------------------

一维数组 是一个对象  alert(json.name);

二维数组 是数组里面存的对象  alert(json.length);   alert(json[0].name);

也可以 $arr['abc']['name']='china';        alert(json.abc.name);