index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/ajax.js"></script>
<title></title>
</head>
<body>
<input type="button" onClick="show();" value="Ajax" />
<br />
<div style="width:500px;height:300px;background:yellow;" id="con">
</div>
</body>
</html>
<script type="text/javascript">
function show() {
ajax = createAjax();
ajax.onreadystatechange = function() {
if (ajax.readyState==4 && ajax.status==200) {
var con = document.getElementById('con');
var data = ajax.responseText;
eval("var obj="+data); // eval 执行JS,把接受到的 Json 转换为数组
// {"name":"\u674e\u8339\u661f","email":"liruxing1715@sina.com","date":"1967-01-26 06:04:49"} PHP文件通过json_encode()返回的 json 数据
con.innerHTML = '姓名:'+ obj.name +'<br />Email:'+ obj.email + '<br />日期:'+ obj.date;
}
}
var url = encodeURI('name=李茹星&email=liruxing1715@sina.com&date=' + new Date().getTime());
ajax.open('post', 'test.php');
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.send(url);
}
</script>
ajax.js
var ajax = null;
// 创建 AJAX 对象
function createAjax(){
var request=false;
//window对象中有XMLHttpRequest存在就是非IE,包括(IE7,IE8)
if(window.XMLHttpRequest){
request=new XMLHttpRequest();
if(request.overrideMimeType){
request.overrideMimeType("text/xml");
}
//window对象中有ActiveXObject属性存在就是IE
}else if(window.ActiveXObject){
var versions=['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
for(var i=0; i<versions.length; i++){
try{
request=new ActiveXObject(versions[i]);
if(request){
return request;
}
}catch(e){
request=false;
}
}
}
return request;
}
![](http://hi.csdn.net/attachment/201201/20/0_1327053192s14D.gif)