實(shí)例一(Ajax請(qǐng)求基本創(chuàng)建格式):
<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Ajax練習(xí)(GET,不考慮瀏覽器兼容性)</title> <script type="text/JavaScript"> function doRequest() { //不考慮瀏覽器兼容性問(wèn)題 var xmlHttp = new XMLHttpRequest(); //打開(kāi)一個(gè)與Http服務(wù)器的連接 xmlHttp.open("GET", "Default.aspx", true); //與服務(wù)器端交互 xmlHttp.send(null); //監(jiān)聽(tīng)服務(wù)器端響應(yīng)狀態(tài)的改變事件 xmlHttp.onreadystatechange = function () { //客戶(hù)端與服務(wù)器端交互完成 if (xmlHttp.readyState == 4) { //服務(wù)器端返回Http狀態(tài)碼:200表示請(qǐng)求成功,404未找到,403錯(cuò)誤 if (xmlHttp.status == 200) { //獲得服務(wù)器端資源 var result = xmlHttp.responseText; alert(result); } } } } </script></head><body> <form id="form1" runat="server"> <div> <input type="button" id="btn" value="異步請(qǐng)求" onclick="doRequest()" /> </div> </form></body></html>
<head runat="server"> <title>AjaxDemo實(shí)例</title> <script src="JS/jQuery-1.4.1-vsdoc.js" type="text/javascript"></script> <script type="text/javascript"> //使用Ajax讀取瀏覽器的工作內(nèi)容 function readRequest() { //不考慮瀏覽器的兼容性問(wèn)題 var xmlhttp = new XMLHttpRequest(); //打開(kāi)一個(gè)與服務(wù)器相關(guān)的鏈接 //發(fā)送請(qǐng)求 //請(qǐng)求的方式(獲取/發(fā)送),請(qǐng)求頁(yè)面,是否異步 xmlhttp.open("GET", "AjaxDemo.aspx", true); //發(fā)送數(shù)據(jù) xmlhttp.send(null); //接受服務(wù)器返回結(jié)果 xmlhttp.onreadystatechange = function() { //請(qǐng)求完成 if (xmlhttp.readyState == 4) { //鏈接成功 if (xmlhttp.status == 200) { //輸出瀏覽器的內(nèi)容 var result = xmlhttp.responseText; alert(result); window.alert("讀取瀏覽器的內(nèi)容成功!"); } } }; }; function btn_Click() { var http = new ActiveXObject("Microsoft.XMLHTTP"); //或者使用這一句創(chuàng)建 var xmlhttp = new XMLHttpRequest(); if (!http) { alert("創(chuàng)建xmlhttp對(duì)象異常!"); return false; } http.open("POST", "AjaxDemo.ashx", false); http.onreadystatechange = function() { if (http.readyState == 4) { //鏈接成功 if (http.status == 200) { alert(http.responseText); document.getElementById("Text1").value = http.responseText; } else { window.alert("Ajax服務(wù)器返回錯(cuò)誤!"); } } }; http.send(); }; </script></head><body> <form id="form1" runat="server"> <div> <input id="Button1" type="button" value="使用Ajax讀取瀏覽器的內(nèi)容" onclick="readRequest()" /> <br/> <input id="Text1" type="text" /> <input id="Button2" type="button" value="獲取當(dāng)前時(shí)間" onclick="btn_Click()"/> </div> </form></body>
新聞熱點(diǎn)
疑難解答
圖片精選