利用微软自带的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>