利用微軟自帶的ajax框架現在有些麻煩,還不好用,並且效果也不是很好,所以選擇用Jquery中的ajax方法來進行異步獲取數據。利用jquery的ajax主要有load,get,post,ajax,getJSON方式來異步獲取數據。
1、$("#xxx").load ( url, [data], [callback] );會將異步獲取的數據直接加入jquery對象中。
2、$.get ( url, [data], [callback] );使用GET方式來進行異步請求。
3、$.post ( url, [data], [callback], [type] ) ;使用POST方式來進行異步請求。
4、$.ajax(options);通過 HTTP 請求加載遠程數據
5、$.getJSON("url");通過get方式跨域來進行異步請求。
總結:在通過異步調用的過程中,更清楚的了解在server是如何來接收client端傳來的數據方式,如,使用get傳送數據時,server端使用Request.QueryString[""]方式來接收,使用post傳送數據時,server端使用Request.Form[""]方式來接收。如果不清楚client端使用什么方式傳送數據,只知道參數名,可使用Request[""]來接收數據,Request[""]接收get方式和post方式傳送至server的數據。
使用jquery的ajax傳送至server的data,是以json方式傳送,其實至server端時,也會被解析為$參數名=參數值&的方式追加至url,如下列注釋所講:Get和post方式的時候data數據有兩種傳送方式:1、name=John&location=Boston;查詢字符串。2、name: 'John', location: 'Boston';映射。數據在發送器會被轉換成查詢字符串
示例:
被異步調用頁面,
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Runtime.Serialization; namespace WebDBMaster.AjaxService { /// <summary> /// $codebehindclassname$ 的摘要描述 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class GetData : IHttpHandler { public void ProcessRequest(HttpContext context) { string test = ""; if (context.Request["loadname"] != null) { test = "這是來自服務器的數據,您是通過Load方式進行的AJAX," + context.Request["loadname"].ToString() + ",您好!"; } if (context.Request["username"] != null) { test = "這是來自服務器的數據,您是通過Get方式進行的AJAX," + context.Request["username"].ToString() + ",您好!"; } if (context.Request["name"] != null) { test = "這是來自服務器的數據,您是通過Post方式進行的AJAX," + context.Request["name"].ToString() + ",您好!"; } if (context.Request["Loading"] != null) { for (int i = 0; i < 30000; i++) { test += i.ToString(); } } context.Response.ContentType = "text/plain"; context.Response.Write(test); } public bool IsReusable { get { return false; } } } }
前端html頁面:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxWeb.aspx.cs" Inherits="WebDBMaster.AjaxWeb" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="Script/jquery-1.7.2.min.js" type="text/javascript"></script> <style type="text/css"> * { margin: 0px; padding: 0px; } .ajax { } .ajaxResult { } .hidDiv { width: 100%; height: 100%; z-index: 5; display: none; background-color: White; position: absolute; filter: alpha(Opacity=80); -moz-opacity: 0.5; opacity: 0.5; } </style> </head> <body> <form id="form1" runat="server"> <div class="ajax ajaxResult"> <div id="msgDiv" class="hidDiv"> <div style="text-align: center; padding: 200px 0 0 0;"> <img src="Images/loading.gif" alt="" /> </div> </div> <input type="button" id="btnOk" value="ajaxLoading" onclick="ajaxHandle();" title="使用Jquery的ajax方法異步訪問服務器時時間比較長的情況下會出現Loading圖片。" /> <input type="button" id="btnSend" value="getJSON" onclick="getJSONP();" title="使用Jquery的getJSON方法異步訪問服務器"/> <input type="button" id="btnGet" value="ajaxGet" onclick="GetAjax();" title="使用Jquery的get方法異步訪問服務器"/> <input type="button" id="btnPost" value="ajaxPost" onclick="PostAjax();" title="使用Jquery的post方法異步訪問服務器"/> <input type="button" id="btnLoad" value="ajaxLoad" onclick="LoadAjax();" title="使用Jquery的load方法異步訪問服務器"/> </div> <div id="MsgDiv" style=" background-color:Gray; width:270px; height:50px; display:none;"></div> </form> <script type="text/javascript"> var icount = 0; function getJSONP() { $.getJSON("http://跨域WCF服務/方法名?callback=?&userId=xxxxxx") .success(function(strJSON) { var json = eval('(' + strJSON + ')'); if (json.length !== 0) { for (var i = 0; i < json.length; i++) { datarow = json[i]; 給html控件綁值; } } }) .error(function() { }) .complete(function() { }) ; } function ajaxHandle() { $.ajax({ type: "get", //以get方式異步請求,也可改為以post方式異步請求。 url: "/AjaxService/GetData.ashx?Loading=true", //請求的url beforeSend: function(XMLHttpRequest) { ShowLoading(); //發送請求前,可在此處讓等待gif顯示 }, complete: function(XMLHttpRequest, textStatus) { HideLoading(); //請求結束,在此讓等待gif隱藏 },
success: function(data, textStatus) {
//alert(data);
//alert(textStatus);
//$(".ajax.ajaxResult").html("");
//$("item", data).each(function(i, domEle) {
//$(".ajax.ajaxResult").append("<li>" + $(domEle).children("title").text() + "</li>"); //});
$("#msgDiv").text(data);
},
error: function(ex) { alert(ex); //請求出錯處理 } }); } function ShowLoading() { $("#msgDiv").show(); } function HideLoading() { $("#msgDiv").hide(); } //Get和post方式的時候data數據有兩種傳送方式:1、name=John&location=Boston;查詢字符串。2、name: 'John', location: 'Boston';映射。數據在發送器會被轉換成查詢字符串 function GetAjax() {//jQuery.get(url,[data],[callback]) $.get('/AjaxService/GetData.ashx', { username: 'hao' }, function(data) { alert(data); }); } function PostAjax() {//jQuery.post(url,[data],[callback],[type]) //$.post('/AjaxService/GetData.ashx', 'name=John&location=Boston', function(data) { alert(data); }); //$.post('/AjaxService/GetData.ashx', { 'name': 'John', 'location': 'Boston' }, function(data) { alert(data); }); $.post('/AjaxService/GetData.ashx', { name: 'John', location: 'Boston' }, function(data) { alert(data); }); } function LoadAjax() {//jQuery.load(url,[data],[callback]) icount++; // $("#MsgDiv").load("/AjaxService/GetData.ashx .get/.post", { username: 'hao' }); $("#MsgDiv").load("/AjaxService/GetData.ashx", { loadname: 'hao' + icount }, function(responseText, textStatus, XMLHttpRequest) { this; //在這里this指向的是當前的DOM對象,即$(".ajax.load")[0] //alert(responseText);//請求返回的內容 //alert(textStatus);//請求狀態:success,error //alert(XMLHttpRequest);//XMLHttpRequest對象 $("#MsgDiv").show(); setInterval(HideDivMsg, 5000); }); } function HideDivMsg(){ $("#MsgDiv").hide(); } </script> </body> </html>