今天学到了json,感觉比传统的ajax实现方法更灵活,更节省流量。据说现在大的互联网公司都是使用的json来实现ajax,可见这种方式有它优秀的地方。
前台页面:
<html>
<head>
<script type="text/javascript">
function ajax(){
	var xmlhttp;
	if (window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
		if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
			//接收后台返回的数据(字符串)
			var data = xmlhttp.responseText;
			//把数据转换成字符串类型的js代码
			var str = ‘var obj = ‘+data;
			//把str当作js代码来运行,产生一个新的obj对象
			eval(str);
			//alert(obj.name);
			var code = ‘姓名:’+obj.name+'<br />性别:’+obj.gender+'<br />年龄’+obj.age;
			alert(code);
		}
	}
	xmlhttp.open("GET",’re.php’,true);
	xmlhttp.send();
}
</script>
</head>
<body>
<input type="button" value="submit" onclick="ajax()" />
</body>
</html>
后台程序re.php:
<?php
//定义一个数组
$arr = array(
	'name'=>'mogu',
	'age'=>22,
	'gender'=>'male',
);
//转换成json格式并输出
echo json_encode($arr);
?>