(JQuery Ajax : http://jun1986.iteye.com/blog/1399242 和 http://www.cnblogs.com/yeer/archive/2009/07/23/1529460.html)
返回方式:
网页片段
javascript片段
数据 (JSON、XML)
<script type="text/javascript"> //XHR的状态 var XHR_STATE_UNINITIALIZED=0; //XHR.open()还没被调用 var XHR_STATE_LOADING=1; //XHR.open()已经被执行 var XHR_STATE_LOADED=2; //XHR.send()已经被执行 var XHR_STATE_INTERACTIVE=3; //XHR发觉server的数据已经返回了一部分 var XHR_STATE_COMPLETE=4; //XHR发现server已经对请求作出响应,并返回了所有内容,操作结束. //获得XMLHttpRequest对象 function getXMLHttpRequest(){ var xhr=null; if(window.XMLHttpRequest){ xhr=new XMLHttpRequest(); // for firefox/IE7 // alert("firefox"); }else { xhr=new ActiveXObject("Microsoft.XMLHTTP"); // for IE. // alert("IE"); } return xhr; } /** xhr: xhr object url: */ function sendRequest(url) { var xhr=getXMLHttpRequest(); //got a XHR instance. xhr.onreadystatechange=function(){ var state=xhr.readyState; if(state==XHR_STATE_COMPLETE){ var status=xhr.status; //获得HTTP STATUS if(status>=200 && status<=299){ parseCompletedResponse(xhr); }else alert("xhr request error!"); }else{ document.getElementById('result').innerText="please wait...stateid:"+state; //alert("please wait...stateid:"+state); } }; /* xhr.open(methodtype,url,isAsynchronous); methodType: GET/POST/... url: isAsynchronous: 如果为true,则为异步. xhr.send xhr.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded' );*/ // alert("xhr="+xhr+",url="+url); xhr.open('GET',url,true); xhr.send(null); } // dom操作, 把得到响应内容写入对应位置 function parseCompletedResponse(xhr) { var storeDiv=document.getElementById('result'); storeDiv.innerHTML=xhr.responseText; } function getUrl() { //document.getElememtById -> object //document.getElementsByName -> object[] var num=document.getElementsByName("num")[0].value; return "calc?num="+encodeURI(num); } </script> <body> 求平方<br> <form action="" method="post"> 数字:<input type="text" name="num"/> <button onclick="sendRequest(getUrl());">计算</button> <div id="result"/> </form> <a onclick="alert(getXMLHttpRequest());" href="#">test XHR</a> <a onclick="alert(getUrl());" href="#">Generate Url</a> </body>