1:php生成数据
<?php
date_default_timezone_set("PRC");
class Person {
public $name = "";
public $age = "";
}
$e = new Person();
$e->name = "clear";
$e->age = 14;
//生成json数据
echo json_encode($e);
2:javascript获取php数据
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="ajax.js"></script>
<script>
window.οnlοad=function ()
{
var oBtn=document.getElementById('btn1');
oBtn.οnclick=function ()
{
ajax('Person.php', function (str){
var data=JSON.parse(str); //获取的数据是字符串类型,需要转化为json类型
for(var key in data){
alert(key+'->'+data[key]);
}
}, function (){
alert('失败');
});
};
};
</script>
</head>
<body>
<input id="btn1" type="button" value="获取" />
</ul>
</body>
</html>
//以上需要导入js文件,ajax.js
function ajax(url, fnSucc, fnFaild)
{
//1.创建Ajax对象
if(window.XMLHttpRequest)
{
var oAjax=new XMLHttpRequest();
}
else
{
var oAjax=new ActiveXObject("Microsoft.XMLHTTP");
}
//2.连接服务器(打开和服务器的连接)
oAjax.open('GET', url, true);
//3.发送
oAjax.send();
//4.接收
oAjax.onreadystatechange=function ()
{
if(oAjax.readyState==4)
{
if(oAjax.status==200)
{
//alert('成功了:'+oAjax.responseText);
fnSucc(oAjax.responseText);
}
else
{
//alert('失败了');
if(fnFaild)
{
fnFaild();
}
}
}
};
}