本文實例講述了ajax數據傳輸方式。,具體如下:
在異步應用程序中發送和接收信息時,常見的可以選擇以純文本和XML作為數據格式(可參考《jQuery學習筆記之Ajax用法實例詳解》),現在還有一種比較流行的方式:JSON(JavaScript Object Notation)。好了,下面舉例說明這三種數據格式在ajax的異步應用。
一、純文本方式
1、發送/接收數據:
Code is cheap.看代碼:
testJs.js
// 此函數等價于document.getElementById /document.allfunction $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }// 創建 XMLHttpRequest對象,以發送ajax請求 function createXMLHTTP() { var xmlHttp = false; var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]; for (var i = 0; i < arrSignatures.length; i++) { try { xmlHttp = new ActiveXObject(arrSignatures[i]); return xmlHttp; } catch (oError) { xmlHttp = false; //ignore } } // throw new Error("MSXML is not installed on your system."); if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); } return xmlHttp;}var xmlReq = createXMLHTTP();// 發送ajax處理請求(這里簡單驗證用戶名和密碼的有效性,默認正確的輸入:用戶名和密碼都是test)function validatePwd(oTxt) { var url = "/AjaxOperations.aspx"; xmlReq.open("post", url, true); xmlReq.setRequestHeader("Content-Length", oTxt.value.length + $("txtUserName").value.length); xmlReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlReq.onreadystatechange = callBack; xmlReq.send("action=chkPwd&userInfos=" + escape(oTxt.value + "/" + $("txtUserName").value)); // 發送文本}function callBack() { if (xmlReq.readyState == 4) { if (xmlReq.status == 200) { alert(xmlReq.responseText); // 接收文本 } else if (xmlReq.status == 404) { alert("Requested URL is not found."); } else if (xmlReq.status == 403) { alert("Access denied."); } else alert("status is " + xmlReq.status); }}幾個附加文件源碼:
jsTest.htm
<html><head><title>js test</title> <script src="js/testJs.js" type="text/javascript"></script> </head><body><form id="form1"><div> 用戶名:<input id="txtUserName" name="txtUserName" type="text" /> 密碼:<input id="txtPwd" name="txtPwd" type="password" onblur="validatePwd(this)" /></div></form></body></html>
AjaxOperations.aspx
代碼如下:<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxOperations.aspx.cs" Inherits="WebTest2008.AjaxOperations" %>
新聞熱點
疑難解答
圖片精選