比较好的一篇ajax原理:适合初学者 ??http://www.cnblogs.com/mingmingruyuedlut/archive/2011/10/18/2216553.html?
?
关于同步和异步的解释:?http://www.cnblogs.com/lebronjames/archive/2010/10/09/1846690.html?
?
关于详细的XMLHttpRequest对象的介绍: ?http://baike.baidu.com/view/1105115.htm?fr=aladdin
?
?
下面是一个输入邮编号通过XMLHttpReqeust对象异步获取邮编所在的城市和地区信息的简单例子:
?
帖出部分核心JS代码
<script type="text/javascript">
var xmlHttp ; //保存XMLHttpRequest对象的全局变量
function createXmlHttp(){
//根据window.XMLHttpRequest对象是否存在使用不同的创建方式
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest(); //FF或者Oper等浏览器创建方式
}else if(window.ActiveXObject){
xmlHttp = new ActiveXObejct("Micorsoft.XMLHTTP"); //IE浏览器创建方式
}
}
//校验输入邮编只能输入数字
function checkNumber(){
if(event.keyCode>=48 && event.keyCode<=57){
event.returnValue =true;
}else{
event.returnValue = false;
}
}
//获取信息的调用函数
function getPostalCode(){
var pCodeValue = document.getElementById("postalCode").value;
alert(pCodeValue);
if(pCodeValue.length==6){
createXmlHttp(); // 创建XMLHttpRequest对象
//onreadystatechange属性:每次 readyState 属性改变的时候调用的事件句柄函数
//readyState属性:HTTP 请求的状态.当一个 XMLHttpRequest 初次创建时,这个属性的值从 0 开始,
//直到接收到完整的 HTTP 响应,这个值增加到 4
xmlHttp.onreadystatechange=function(){ //获取地区信息的回调函数
//成功返回
if(xmlHttp.readyState==4 && xmlHttp.status==200){
var areaInfo = xmlHttp.responseText; //获取服务器返回的信息
console.info(areaInfo);
if(areaInfo!=""){
var arr = areaInfo.split("|");
alert(arr[0]);
alert(arr[1]);
document.getElementById("area").value=arr[0];
document.getElementById("city").value=arr[1];
}
}
};
xmlHttp.open("GET","postalcode.jsp?postalCode="+ pCodeValue,true);
xmlHttp.send(null);
}
}
</script>
?
前端Html代码:
?
<body>
<h3>邮编测试</h3>
<p>邮编:<input id="postalCode" onkeypress="checkNumber()" type="text" onblur="getPostalCode()"/></p>
<p>地区:<input id="area" type="text" /></p>
<p>城市:<input id="city" type="text" /></p>
</body>
?
?
?
原文:http://henu-zhangyang.iteye.com/blog/2235422