jQuery為AJax提供了非常豐富的支持,參見AJax
其中最基本當屬$AJax(),通過不同的
參數,這個方法可以錄活支持各種AJax應用場景。如:
$.AJax({ url: "test.html", cache: false, success: function(html){ $("#results").append(Html); } }); 完整參數列表參見:options 當然,常用的應該是這些:
DEMO:
建一個GenericHandler作AJax請求服務端:CubeHandler.ashx
<%@ WebHandler Language="C#" Class="CubeHandler" %> using System; using System.Web; public class CubeHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; int number = 0; int.TryParse(context.Request.Params["number"], out number); context.Response.StatusCode = 200; context.Response.Cache.SetCacheability (HttpCacheability.NoCache); context.Response.Write(string.Format("{0} cubed is {1}",number,Math.Pow(number, 3))); } public bool IsReusable { get { return true; } } }
因為用的是Request.Params,所以這個handler能同時支持get和post,
<!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> <title>AJax</title> <script src="../scripts/jquery-1.2.3.intellisense.JS" type="text/Javascript"></script> <script type="text/Javascript"> $(function(){ //設置指示器 $('#divIndicator').ajaxStart(function(){$(this).show()}) .ajaxSuccess(function(){$(this).hide()}) .ajaxError(function(msg){$(this).hide();alert(msg);}); //ajax get 請求 $('#btnGetCubeInGet').click(function(){ var number = $('#txtNumber').val(); $.get('CubeHandler.ashx?number='+number,function(result){ alert(result); }); }); //AJax post 提交 $('#btnGetCubeInPost').click(function(){ var number = $('#txtNumber').val (); $.get('CubeHandler.ashx',{'number':number},function(result){ alert(result); }); }); }); </script> <style type="text/CSS"> .indicator { color: #FF0000; position: absolute; top: 0px; right: 0px; display: none; } </style> </head> <body> <div id="divIndicator" class="indicator"> <img src="indicator.gif" />loading</div> plz input a number:<input id="txtNumber" /> <input type="button" id="btnGetCubeInGet" value="Get cube(get)" /> <input type="button" id="btnGetCubeInPost" value="Get cube(post)" /> </body> </Html>