今天回顧了一下js的ajax調用,寫了個小示例:
JS代碼:
- <script type="text/javascript">
- //調用函數
- function getMsg() {
- createXMLHttpRequest();
- var name = "Marx";
- var url = "hdHelloWorld.ashx?Name=" + name; //URL地址:這裏訪問的是一個一般處理程序文件
- xmlReq.open("GET", url, false); //以GET的方式訪問
- xmlReq.onreadystatechange = OnMessageBack; //設置回調函數
- xmlReq.send(null); //發送請求
- }
- //回調函數
- function OnMessageBack() {
- if (xmlReq.readyState == 4) {
- if (xmlReq.status == 200) {//調用成功,返回結果
- sum = xmlReq.responseText;
- document.getElementById("div1").innerHTML = sum;//將返回的結果寫到DIV中
- }
- }
- }
- // 創建一個ActiveXObject 對象使現局部請求到服務器
- function createXMLHttpRequest() {
- if (window.XMLHttpRequest) {
- xmlReq = new XMLHttpRequest();
- if (xmlReq.overrideMimeType)
- xmlReq.overrideMimeType('text/xml');
- }
- else if (window.ActiveXObject) {
- try {
- xmlReq = new ActiveXObject('Msxml2.XMLHTTP');
- }
- catch (e) {
- try {
- xmlReq = new ActiveXObject('Microsoft.XMLHTTP');
- }
- catch (e) {
- }
- }
- }
- }
- </script>
一般處理程序hdHelloWorld.ashx中的代碼:
- public void Proce***equest (HttpContext context) {
- string name = context.Request.QueryString["Name"];
- context.Response.Write("Hello " + name+"!");
- }
HTML代碼:
- <input type="button" value="GetMsg" onclick="getMsg();" />
- <div id="div1"></div>
點擊“GetMsg”按鈕,就會通過ajax調用,獲取到數據。僅供參考。