標籤:
JQuery版本的ajax請求:(包括處理WebService中xml字串)
1 $.ajax({ 2 type: "POST", 3 async: true, 4 url: "", 5 data: "", 6 success: function (data) { 7 data = data.replace("<string xmlns=\"http://tempuri.org/\">", "").
replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>").
replace("</string>", "").replace("undefined", "").
replace(";", "").replace(/</g, ‘<‘).
replace(/>/g, ‘>‘).replace("<", "<").
replace(/&/g, "&").replace(/&/g, "&").
replace(/\n/g, "").
replace(/\r/g, ""); 8 9 },10 error: function () {11 12 },13 dataType: "html"14 });
Js版本的ajax請求:
common.js
//由於瀏覽器版本不同影響Ajax不同,所以遇到不同的版本需要new不同的Ajax//建立一個Ajax對象function createXmlHttp() { var xhobj = false; try { xhobj = new ActiveXObject("Msxml2.XMLHTTP"); // ie msxml3.0+ } catch (e) { try { xhobj = new ActiveXObject("Microsoft.XMLHTTP"); //ie msxml2.6 } catch (e2) { xhobj = false; } } if (!xhobj && typeof XMLHttpRequest != ‘undefined‘) {// Firefox, Opera 8.0+, Safari xhobj = new XMLHttpRequest(); } return xhobj;}
本文:
get提交:
<!--引進來Common.js --> <script src="Scripts/Common.js" type="text/javascript"></script> <script type= "text/javascript"> var aj = false; window.onload = function () { //new一個Ajax aj = createXmlHttp(); } //Ajax函數 GET提交 function doAjax() { //開啟串連 //需要使用多個參數,第一個設定方法屬性,第二個設定目標URL,第三個指定是同步(false)還是非同步(true)發送請求 var url = ""; aj.open("GET", url, true); //設定回呼函數[即:需要接受伺服器返回的值] //讀取狀態改變 aj.onreadystatechange = function () { alert(aj.readyState); if (aj.readyState >= 4) { if (aj.status == 200) {//狀態代碼為200正常響應
} else {
} } }; //發送[get發送為空白] aj.send(null); } </script>
post提交:
<script src="Scripts/Common.js" type="text/javascript"></script> <script type="text/jscript" > var aj = false; window.onload = function () { aj = createXmlHttp(); } //Ajax函數 Post提交 function doAjax() { var url = "Js_Login.aspx"; //如果提交的值是中文,需要編碼 //encodeURI() 或 encodeURIComponent() var user = encodeURI(gel("txt").value); var pwd = gel("pwd").value; var data = "user=" + user + "&pwd=" + pwd; //開啟串連 aj.open("POST", url, true); //需要設定要求標頭 aj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //回呼函數 aj.onreadystatechange = function () { if (aj.readyState >= 4) { if (aj.status == 200) { //狀態代碼為200正常響應 var txt = aj.responseText; //接受資料 }
else {
} } } //發送資料[Post發送不可為空] aj.send(data); } </script>
常用ajax請求