您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“AJAX的調(diào)用方式實(shí)例”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“AJAX的調(diào)用方式實(shí)例”吧!
實(shí)例一:省份-城市的聯(lián)級(jí)下拉框
利用AJAX來(lái)獲取數(shù)據(jù)實(shí)現(xiàn)聯(lián)級(jí)下拉框,當(dāng)省份下拉框的選項(xiàng)發(fā)生變化時(shí),城市的選項(xiàng)對(duì)應(yīng)變化,效果如圖:
我們首先來(lái)實(shí)現(xiàn)后臺(tái),先將數(shù)據(jù)準(zhǔn)備好了在實(shí)現(xiàn)前臺(tái)獲取數(shù)據(jù),【考慮:當(dāng)我們頁(yè)面登錄的時(shí)候,我們需要獲取的數(shù)據(jù)】: 1).省份框中的省份; 2).因?yàn)榈卿洉r(shí)省份框的第一項(xiàng)選中,所以還需要第一個(gè)省份所對(duì)應(yīng)的城市名,好了,需求知道了,代碼就好寫(xiě)了,直接貼上后臺(tái)代碼:
protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["provid"] != null) { //首先獲取傳遞過(guò)來(lái)的參數(shù)值 string provId = Request.QueryString["provid"].ToString(); //查詢(xún)所有城市 string sqlprov = "select * from Provice"; SqlDataReader reader = DbHelperSQL.ExecuteReader(sqlprov); string resultProv = ""; while (reader.Read()) { string id = reader[0].ToString(); string provName = reader[1].ToString(); //字符串拼接,為了前臺(tái)獲取時(shí)可以切分獲取對(duì)應(yīng)數(shù)據(jù),用 '|' 來(lái)隔離 各個(gè)省份 resultProv += "|" + string.Format("{0},{1}", id, provName); } reader.Close(); //根據(jù)省份框的ID來(lái)獲取對(duì)應(yīng)的城市名 string sqlcity =string.Format("select * from City where Proid='{0}'",provId); SqlDataReader readercity = DbHelperSQL.ExecuteReader(sqlcity); string resultCity = ""; while (readercity.Read()) { string cityId = readercity[1].ToString(); string cityName = readercity[2].ToString(); //同樣用字符串拼接 用 '|' 來(lái)隔離 同一省份 的各個(gè)城市 resultCity += "|" + string.Format("{0},{1}", cityId, cityName); } //去除第一個(gè) '|' ,并且在最后拼接上 '&' 來(lái)區(qū)分省份和城市 resultProv = resultProv.Substring(1) + "&"; //最后的結(jié)果形式為【id,省份名|id2,省份名2|....&id,城市名|id2,城市名2|.....】 string result = resultProv + resultCity.Substring(1); Response.Write(result); Response.End(); } }
后臺(tái)代碼其實(shí)很簡(jiǎn)單,就是根據(jù)傳過(guò)來(lái)的參數(shù)從數(shù)據(jù)庫(kù)獲取對(duì)應(yīng)的數(shù)據(jù),但是這里我們把獲取到得數(shù)據(jù)最后都用字符串拼接起來(lái)了,而且是有規(guī)律的拼接,這是為什么呢?其實(shí)在注釋上已經(jīng)講明了,就是為了方便前臺(tái)獲取對(duì)應(yīng)的數(shù)據(jù)了,因?yàn)槲覀兪鞘褂煤笈_(tái)返回文本形式的數(shù)據(jù),這就是為什么我們拼接字符串了。。
接下來(lái)我們來(lái)實(shí)現(xiàn)前臺(tái),前臺(tái)主要的任務(wù)就是獲取后臺(tái)返回的數(shù)據(jù),并實(shí)現(xiàn)綁定......也是分塊貼上代碼
//實(shí)例化XmlHttpRequest對(duì)象 var xhr = null; function CreateXhr() { if (window.ActiveXObject) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xhr = null; } } } if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } return xhr; }
當(dāng)頁(yè)面載入時(shí),實(shí)現(xiàn)省份框以及第一個(gè)省份對(duì)應(yīng)的城市框的綁定,代碼:
//載入綁定省份 function getLoadProv() { CreateXhr(); xhr.onreadystatechange = WatchState; xhr.open("get", "getProvCity.aspx?provid=1&time=" + new Date()); xhr.send(null); } //監(jiān)聽(tīng)載入綁定時(shí)狀態(tài) function WatchState() { if (xhr.readyState == 4 && xhr.status == 200) { //1,**|2,**&1,##|2,## var result = xhr.responseText; var provs = result.split('&')[0].split('|'); var citys = result.split('&')[1].split('|'); //省份下拉框清空 document.forms[0].prov.length = 0; //綁定省份框 for (var i = 0; i < provs.length; i++) { var prov = provs[i].split(','); //實(shí)例化一個(gè)選項(xiàng) var op = new Option(); op.value = prov[0]; op.text = prov[1]; document.forms[0].prov.options.add(op); } //城市下拉框清空 document.forms[0].city.length = 0; //綁定城市框 for (var j = 0; j < citys.length; j++) { var city = citys[j].split(','); var op = new Option(); op.value = city[0]; op.text = city[1]; document.forms[0].city.options.add(op); } } }
當(dāng)省份框的選項(xiàng)發(fā)生變化時(shí)實(shí)現(xiàn)聯(lián)級(jí)變化,代碼:
//獲取城市 function GetCity() { //獲取省份框選中的值 var provId = document.forms[0].prov.value; CreateXhr(); xhr.onreadystatechange = UpdateCity; xhr.open("get", "getProvCity.aspx?provid=" + provId + "&time=" + new Date()); xhr.send(null); } //修改城市下拉框內(nèi)容 function UpdateCity() { if (xhr.readyState == 4 && xhr.status == 200) { var result = xhr.responseText; var citys = result.split('&')[1].split('|'); //城市下拉框清空 document.forms[0].city.length = 0; //綁定城市框 for (var j = 0; j < citys.length; j++) { var city = citys[j].split(','); var op = new Option(); op.value = city[0]; op.text = city[1]; document.forms[0].city.options.add(op); } }
前臺(tái)html代碼:
html <body> <form id="form1" runat="server"> <div> <select id="prov" onchange="GetCity();"> </select> <select id="city"> </select> </div> </form> </body>
實(shí)例二:利用$.get,$.post方法獲取當(dāng)前時(shí)間
$.get():
定義:get()方法通過(guò)遠(yuǎn)程HTTP GET請(qǐng)求載入信息
語(yǔ)法:$(selector).get(url,data,success(response,status,xhr),dataType)
參數(shù)
url:必須,請(qǐng)求發(fā)送的地址。
data:可選,發(fā)送到服務(wù)器的數(shù)據(jù)。
success:可選,請(qǐng)求成功時(shí)運(yùn)行的函數(shù)
1).response:包含結(jié)果的數(shù)據(jù)
2).status:包含請(qǐng)求的狀態(tài)
3).xhr:包含XmlHttpRequest對(duì)象
dataType:服務(wù)器響應(yīng)的數(shù)據(jù)類(lèi)型,默認(rèn)將智能判斷
$.post()
定義:post()方法通過(guò)遠(yuǎn)程HTTP Post請(qǐng)求載入信息
語(yǔ)法:$(selector).post(url,data,success(data,status,jqXHR),dataType)
參數(shù)
url:必須,請(qǐng)求發(fā)送的地址。
data:可選,發(fā)送到服務(wù)器的數(shù)據(jù)。
success:可選,請(qǐng)求成功時(shí)運(yùn)行的函數(shù)
1).data:包含結(jié)果的數(shù)據(jù)
2).status:包含請(qǐng)求的狀態(tài)
3).jqXHR:包含XmlHttpRequest對(duì)象
dataType:服務(wù)器響應(yīng)的數(shù)據(jù)類(lèi)型,默認(rèn)將智能判斷
由于實(shí)例相當(dāng)簡(jiǎn)單,直接上所有代碼:
protected void Page_Load(object sender, EventArgs e) { string time = ""; //Get if (Request.QueryString["time"]!=null) { time = "Get:"+ Request.QueryString["time"].ToString(); } //Post if (Request.Form["time"] != null) { time = "Post:" + Request.Form["time"].ToString(); } Response.Write(time + " 現(xiàn)在:" + DateTime.Now.ToString()); Response.End(); }
前臺(tái)獲取時(shí)間
<script src="../Scripts/jquery-1.8.0.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { //參數(shù):直接在頁(yè)面之后加?拼加 $("#btnGet").click(function () { $.get("data.aspx?time=" + new Date(), Succeed); }); //參數(shù):使用鍵值來(lái)表示需要傳遞的參數(shù) $("#btnPost").click(function () { $.post("data.aspx", { time: new Date() }, Succeed); }); }); function Succeed(result) { $("#tbShow").val(result); } </script>
<body> <form id="form1" runat="server"> <div> <input type="text" id="tbShow"/> <input type="button" id="btnGet" value="get方法" /> <input type="button" id="btnPost" value="post方法" /> <input type="button" id="btnAjax" value="ajax方法" /> </div> </form> </body>
實(shí)例三:使用$.ajax實(shí)現(xiàn)獲取后臺(tái)數(shù)據(jù),后臺(tái)返回?cái)?shù)據(jù)格式為text,json,xml三種類(lèi)型
$.ajax()
定義:ajax()方法通過(guò)遠(yuǎn)程HTTP請(qǐng)求載入信息
語(yǔ)法:Jquery.ajax([settings])
常用參數(shù)[settings]--用于配置Ajax的鍵值對(duì)請(qǐng)求
url:必須,請(qǐng)求發(fā)送的地址
type: 請(qǐng)求方式
data:可選,發(fā)送到服務(wù)器的數(shù)據(jù)
success:可選,請(qǐng)求成功時(shí)運(yùn)行的函數(shù)
1).data:包含結(jié)果的數(shù)據(jù)
2).status:包含請(qǐng)求的狀態(tài)
3).jqXHR:包含XmlHttpRequest對(duì)象
dataType:服務(wù)器響應(yīng)的數(shù)據(jù)類(lèi)型,默認(rèn)將智能判斷
其余參數(shù)詳情參見(jiàn):http://www.w3school.com.cn/jquery/ajax_ajax.asp
1>.test格式 --獲取時(shí)間的時(shí),分,秒
后臺(tái)代碼:
public partial class textData : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string hour = DateTime.Now.Hour.ToString(); string minute = DateTime.Now.Minute.ToString(); string second = DateTime.Now.Second.ToString(); string textStr = hour + "/" + minute + "/" + second; Response.Write(textStr); Response.End(); } }
前臺(tái)獲取代碼:
<script src="../Scripts/jquery-1.8.0.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#btnText").click(function () { $.ajax({ url: "textData.aspx", type: "get", dataType: "text", success: textSucceed, error: Error }); }); }); //成功 function textSucceed(result) { $("#tbShow").val(result); } //錯(cuò)誤函數(shù) function Error() { alert("Error!!!"); } </script>
2>.Json格式 --獲取時(shí)間的時(shí),分,秒
我們需要在后臺(tái)返回Json格式的數(shù)據(jù),添加一個(gè)dll鏈接庫(kù),類(lèi)似.Net中處理Json數(shù)據(jù)的API ,如圖:
Json格式后臺(tái)代碼:
Json后臺(tái) //添加引用 using Newtonsoft.Json; namespace AJAX.Json { public partial class jsonData : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string hour = DateTime.Now.Hour.ToString(); string minute = DateTime.Now.Minute.ToString(); string second = DateTime.Now.Second.ToString(); //匿名類(lèi)型 var time = new { h = hour, m = minute, s = second }; //轉(zhuǎn)Json格式 var jsonStr = JsonConvert.SerializeObject(new[] { time }); Response.Write(jsonStr); Response.End(); } } }
Json格式前臺(tái)代碼:
<script src="../Scripts/jquery-1.8.0.js" type="text/javascript"></script> <script type="text/javascript"> $("#btnJson").click(function () { $.ajax({ url: "jsonData.aspx", type: "get", dataType: "json", success: jsonSuccess, error: Error }); }); //成功 function jsonSuccess(result) { //[{h:10,m:20,s:30}] //key:數(shù)組元素下標(biāo)-此時(shí)為0 //value:{ h:10,m:20,s:30 } $.each(result, function (key, value) { var h = value.h; var m = value.m; var s = value.s; $("#tbShow").val(h + ":" + m + ":" + s); }); } //錯(cuò)誤函數(shù) function Error() { alert("Error!!!"); } </script>
3>.xml格式--獲取用戶(hù)名,出生年月
Xml格式后臺(tái)代碼:
//添加引用 using System.Xml; namespace AJAX.Ajax_Xml { public partial class XmlData : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string name = "zld"; string birth = "1990-1-8"; //第一種:直接字符串拼接 string xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><root><Name>" + name + "</Name><Birth>" + birth + "</Birth></root>"; //第二種:XmlDocument創(chuàng)建 //創(chuàng)建文檔 XmlDocument xmlDocument = new XmlDocument(); //文檔頭聲明 XmlDeclaration xd = xmlDocument.CreateXmlDeclaration("1.0","utf-8",null); xmlDocument.AppendChild(xd); //添加根節(jié)點(diǎn) XmlElement root = xmlDocument.CreateElement("root"); xmlDocument.AppendChild(root); //給根節(jié)點(diǎn)添加子節(jié)點(diǎn) XmlElement node1 = xmlDocument.CreateElement("Name"); node1.InnerText = name; root.AppendChild(node1); XmlElement node2 = xmlDocument.CreateElement("Birth"); node2.InnerText = birth; root.AppendChild(node2); //獲取節(jié)點(diǎn)元素 string xmlStr2 = xmlDocument.OuterXml; Response.Write(xmlStr2); Response.End(); } } }
Xml格式前臺(tái)代碼:
<script src="../Scripts/jquery-1.8.0.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#btnXml").click(function () { $.ajax({ url: "XmlData.aspx", type: "get", dataType: "xml", success: Success, error: function (result) { alert("相應(yīng)內(nèi)容非xml格式!"); } }); }); }); function Success(xmlResult) { //獲取返回結(jié)果 var result = xmlResult; //找尋根節(jié)點(diǎn)并循環(huán)遍歷 $(result).find('root').each(function (key) { //獲取子節(jié)點(diǎn)名為Name的值 var name = $(this).children("Name").text(); //獲取子節(jié)點(diǎn)名為Birth的值 var birth = $(this).children("Birth").text(); $("#tbShow").val(name + ":" + birth); }); } </scri
實(shí)例四:ajax調(diào)用wcf獲取數(shù)據(jù)
首先貼上模塊圖:
首先定義好數(shù)據(jù)契約和操作契約,貼上StudentService.svc代碼:
StudentService.svc namespace ajaxwcf { [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class StudentService { // 要使用 HTTP GET,請(qǐng)?zhí)砑?nbsp;[WebGet] 特性。(默認(rèn) ResponseFormat 為 WebMessageFormat.Json) // 要?jiǎng)?chuàng)建返回 XML 的操作, // 請(qǐng)?zhí)砑?nbsp;[WebGet(ResponseFormat=WebMessageFormat.Xml)], // 并在操作正文中包括以下行: // WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; [OperationContract] //獲取學(xué)生數(shù)據(jù) public List<Student> GetStudents() { string sqlConn = ConfigurationManager.ConnectionStrings["SqlConn"].ConnectionString; SqlConnection conn = new SqlConnection(sqlConn); SqlDataAdapter da = new SqlDataAdapter("select * from AJAX_Tab", conn); DataSet ds = new DataSet(); da.Fill(ds); List<Student> Stulis = new List<Student>(); DataTable dt = ds.Tables[0]; Student student = null; foreach (DataRow row in dt.Rows) { student = new Student(); student.Sname = row["sname"].ToString(); student.Sage = row["sage"].ToString(); student.Sadd = row["sadd"].ToString(); Stulis.Add(student); } return Stulis; } } //數(shù)據(jù)契約 [DataContract] public class Student { private string sname; [DataMember] public string Sname { get { return sname; } set { sname = value; } } private string sage; [DataMember] public string Sage { get { return sage; } set { sage = value; } } private string sadd; [DataMember] public string Sadd { get { return sadd; } set { sadd = value; } } } }
在web.config中進(jìn)行配置,上代碼:
web.config <system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="ajaxwcf.StudentServiceAspNetAjaxBehavior"> <enableWebScript /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="MyServiceTypeBehaviors"> <serviceMetadata httpGetEnabled="true" /> </behavior> <behavior name=""> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> <services> <service name="ajaxwcf.StudentService" behaviorConfiguration="MyServiceTypeBehaviors"> <endpoint address="" behaviorConfiguration="ajaxwcf.StudentServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="ajaxwcf.StudentService" /> </service> </services> </system.serviceModel>
好了,這樣wcf就配置好了,接下去就是頁(yè)面端的調(diào)用了,貼上ajax_wcf.aspx前臺(tái)頁(yè)面代碼:
<script type="text/javascript"> //載入WCF function loadWCF() { var student = new StudentService(); arr = student.GetStudents(succeededCallback, filedCallback); } //成功 function succeededCallback(result, userContext, methodName) { var arr = new Array(); arr = result; //動(dòng)態(tài)創(chuàng)建表格信息 并賦值 var table = document.getElementById("ajaxTab"); for (var i = 0; i < arr.length; i++) { var tr = document.createElement("tr"); var td1 = document.createElement("td"); td1.innerHTML = arr[i].Sname; var td2 = document.createElement("td"); td2.innerHTML = arr[i].Sage; var td3 = document.createElement("td"); td3.innerHTML = arr[i].Sadd; tr.appendChild(td1); tr.appendChild(td2); tr.appendChild(td3); table.appendChild(tr); } } //失敗 function filedCallback(error,userContext,methodName) { alert("Error!"); }
這樣整個(gè)項(xiàng)目就完成了,接下去貼效果:
調(diào)用前:
調(diào)用后:
實(shí)例五[補(bǔ)充內(nèi)容]:Json格式數(shù)據(jù)的打包和解包方式
在打包和解包中,我們?nèi)耘f用到了上面提及的Json數(shù)據(jù)API,同樣要先添加引用,由于代碼都有了對(duì)應(yīng)的注釋?zhuān)辉俣嘧鑫淖值馁樖觯苯淤N上代碼和效果吧:
代碼:
namespace Json打包解包方式 { class Program { static void Main(string[] args) { string name = "zld"; int age = 23; string addr = "nb"; //----------------------匿名打包-------------------// //創(chuàng)建匿名類(lèi)型 var temClass = new { Name = name, Age = age, Addr = addr }; Console.WriteLine("----------通過(guò)匿名打包------------"); //打包成單個(gè)Json對(duì)象 var jsonStr1 = JsonConvert.SerializeObject(temClass); Console.WriteLine("打包單個(gè)對(duì)象后:\n{0}", jsonStr1); Console.WriteLine(); //打包成Json數(shù)組 var jsonStr2 = JsonConvert.SerializeObject(new[] { temClass,temClass }); Console.WriteLine("打包Json數(shù)組后:\n{0}", jsonStr2); Console.WriteLine(); //----------------------匿名解包-------------------// Console.WriteLine("----------通過(guò)匿名解包------------"); //匿名解包 var temClass2 = JsonConvert.DeserializeAnonymousType(jsonStr1, temClass); Console.WriteLine("匿名解包后:\n Name={0},Age={1},Addr={2}",temClass2.Name,temClass2.Age,temClass2.Addr); Console.WriteLine(); //提取局部信息 var temClass3 = JsonConvert.DeserializeAnonymousType(jsonStr1, new { Name = name, Addr = addr }); Console.WriteLine("匿名解包局部信息后: \n Name={0},Addr={1}", temClass3.Name, temClass3.Addr); Console.WriteLine(); //解包成數(shù)組對(duì)象【jsonStr2:數(shù)組對(duì)象】 var temClass4 = JsonConvert.DeserializeAnonymousType(jsonStr2, new[] { temClass }); //數(shù)組 foreach循環(huán)遍歷 foreach(var item in temClass4) { Console.WriteLine("匿名解包為數(shù)組后: \n Name={0},Age={1},Addr={2}",item.Name,item.Age,item.Addr); } Console.WriteLine(); //----------------------通過(guò)類(lèi)打包-------------------// //實(shí)例化一個(gè)類(lèi)對(duì)象 MyObj mo = new MyObj() { Name = name, Age = age, Addr = addr }; Console.WriteLine("----------通過(guò)類(lèi)打包------------"); //單個(gè)對(duì)象打包 var temClass5 = JsonConvert.SerializeObject(mo); Console.WriteLine("類(lèi)打包后:\n{0}", temClass5); Console.WriteLine(); //打包成集合(數(shù)組 泛型) var temClass6 = JsonConvert.SerializeObject(new[] { mo,mo }); Console.WriteLine("類(lèi)打包成數(shù)組后:\n{0}", temClass6); Console.WriteLine(); var temClass7=JsonConvert.SerializeObject(new List<MyObj>{mo,mo}); Console.WriteLine("類(lèi)打包成泛型后:\n{0}", temClass6); Console.WriteLine(); Console.WriteLine("----------通過(guò)類(lèi)解包------------"); var temClass8 = JsonConvert.DeserializeObject<MyObj>(temClass5); Console.WriteLine("類(lèi)解包單個(gè)對(duì)象后:\n Name={0},Age={1},Addr={2}", temClass8.Name, temClass8.Age, temClass8.Addr); Console.WriteLine(); var temClass9 = JsonConvert.DeserializeObject<List<MyObj>>(temClass6); foreach(MyObj item in temClass9) { Console.WriteLine("類(lèi)解包泛型后:\n Name={0},Age={1},Addr={2}", item.Name, item.Age, item.Addr); } Console.ReadKey(); } } //定義一個(gè)類(lèi)型 public class MyObj { public string Name { get; set; } public int Age { get; set; } public string Addr { get; set; } } }
效果圖:
到此,相信大家對(duì)“AJAX的調(diào)用方式實(shí)例”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢(xún),關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。