示例:
第一步:創建XMLHttpRequest對象
var httpxml ; if(window.XMLHttpRequest){ //大多數瀏覽器 httpxml = new XMLHttpRequest(); }else{ //古董級瀏覽器 httpxml = new ActiveXObject("Microsoft.XMLHTTP"); }
第二步:向服務器發送請求
使用 XMLHttpRequest 對象的 open() 和 send() 方法。具體參數,如下所示:
使用方法:
GET使用方法:
xmlhttp.open("GET","URL",true);
xmlhttp.send();
POST使用方法
xmlhttp.open("POST",“URL”,true);
xmlhttp.send();
如果 post 請求中帶參數需使用setRequestHeader() 來添加 HTTP 頭。
xmlhttp.open("post","url",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
第三步:使用 onreadystatechange 事件監聽狀態變化,並獲取服務器響應
xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ document.getElementById("容器").innerHTML = xmlhttp.response.Text; } }
服務器響應有兩種形式: responseText 或 responseXML 。
responseText代表獲得字符串形式的響應數據。
responseXML代表獲得 XML 形式的響應數據
狀態:
(1)readyState存有XMLHttpRequest 的狀態,0~4。
0——請求未初始化
1——服務器連接已經建立
2——請求已接受
3——請求處理中
4——請求已完成,且響應已就緒。
(2)status,HTTP的特定狀態碼:
100-199:信息性的標示用戶應該采取的其他動作。
200-299:表示請求成功。
300-399:用於那些已經移走的文件,常常包括Location報頭,指出新的地址。
400-499:表明客戶引發的錯誤。
500-599:由服務器引發的錯誤。
使用GET方法的具體代碼
<script> var httpxml ; if(window.XMLHttpRequest){ //大多數瀏覽器 httpxml = new XMLHttpRequest(); }else{ //古董級瀏覽器 httpxml = new ActiveXObject("Microsoft.XMLHTTP"); } httpxml.onreadystatechange =function () { if(httpxml.readyState==4 && httpxml.status==200){ console.log(httpxml) }else{ console.log("發生了錯誤"); } } httpxml.open("get","http://localhost:8080/ServletDemo",true); httpxml.send(); </script>
使用POST的方法具代碼
<script> var httpxml ; if(window.XMLHttpRequest){ //大多數瀏覽器 httpxml = new XMLHttpRequest(); }else{ //古董級瀏覽器 httpxml = new ActiveXObject("Microsoft.XMLHTTP"); } httpxml.onreadystatechange =function () { if(httpxml.readyState==4 && httpxml.status==200){ console.log(httpxml) }else{ console.log("發生了錯誤"); } } httpxml.open("post","http://localhost:8080/ServletDemo",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); httpxml.send("name='參數1'&name1='參數2'"); </script>