(四)Ajax的实现(3中Ajax的实现, 需要说明的是: Ajax能够实现的效果, 通过WebService都能实现.)
1. Js中的Ajax异步调用: a.new b.onreadystatechange(处理responseText) c.open(get方式和post方式) d.send (同步调用: a.new b.open(get方式和post方式) c.send d.responseText)
//ajax.html
<!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 of Javascript & jQuery</title></head><body><a href="javascript:getData();">Javascript-Ajax: Click me</a><br /><br /><br /><input id="btn" type="button" value="jQuery-Ajax: Clike me"/><hr /><div id="show"></div><script type="text/javascript">function getData() {//创建XMLHttpRequest通信对象var xhr;if (window.ActiveXObject) { //标准情况下, 只能有两个ActiveXObject对象处理通信过程xhr =new ActiveXObject("Microsoft.XMLHTTP");}elseif (window.XMLHttpRequest) {xhr =new XMLHttpRequest();}else {thrownew Error("Ajax is not supported by this browser");}var elem = document.getElementById("show"); //用来显示处理结果//使用onreadystatechange事件处理结果xhr.onreadystatechange =function() {if (xhr.readyState ==4) { // readyState表示服务器响应状态. 4: 响应接收完毕if (xhr.status ==200) { // status 表示 http 请求的状态var json = xhr.responseText; //从请求中回应中获得json串var obj = eval("("+ json +")"); // 借助 eval 将 json 串转化为对象, 在客户端浏览器必须解析为js对象elem.innerHTML ="<span>"+ obj.name +"</span>";}}}//通过open设置请求方式xhr.open("get", "json.ashx", true); //默认为ture, false表示同步方式//发送请求xhr.send(null);/* 同步方式, false表示不适用异步方式xhr.open("get", "json.ashx", false);xhr.send(null);//处理结果alert(xhr.responseText);*/}</script><script src="jquery-1.4.2.js" type="text/javascript"></script><script type="text/javascript">$(function() { //ready函数, 脚本加载完即执行, 也可以用$(...$("#btn").click...)();加载$("#btn").click(function showData() { //按钮上添加onclick事件, 事件处理方法为showData()$("#show").load("jquery.ashx"); //从jquery.ashx中获取数据元素(innerHTML的内容), 并显示在div中});});</script></body></html>然后还需要在项目中, 添加类似于json.ashx一般处理程序, 用于提供相关数据(如: 表格日历的绘制, 去数据库验证等操作)
<%@ WebHandler Language="C#" Class="Json"%>using System;using System.Web;publicclass Json : IHttpHandler {publicvoid ProcessRequest (HttpContext context) {context.Response.ContentType ="text/plain";//对于静态内容, 需要禁用浏览器的缓存, 否则老是旧结果context.Response.Cache.SetCacheability(HttpCacheability.NoCache);string name ="Mike";string jsonFormat ="{{ "name": "{0}" }}"; //{{、}}是为了避免和Json中的{冲突而采用的特殊转义符string json =string.Format(jsonFormat, name);context.Response.Output.Write(json);}publicbool IsReusable {get {returnfalse;}}}//jquery.ashx
<%@ WebHandler Language="C#" Class="jquery"%>using System;using System.Web;publicclass jquery : IHttpHandler {publicvoid ProcessRequest (HttpContext context) {context.Response.ContentType ="text/plain";context.Response.Cache.SetCacheability(HttpCacheability.NoCache);DateTime now = DateTime.Now;string jqueryFormat ="<span>{0}</span>";string jquery =string.Format(jqueryFormat, now);context.Response.Write(jquery);}publicbool IsReusable {get {returnfalse;}}}2.1 使用AjaxPro2:
<location path="ajaxpro"><system.web><httpHandlers><add verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/></httpHandlers><!--If you need to have Ajax.NET Professional methods running on thelogin page you may have to enable your own authorization configurationhere.--><!--<authorization><deny users="?"/></authorization>--></system.web></location>//c.在App_Code中创建类库文件(cs文件)提供Ajax服务, 并在页面对应的后台cs文件中注册Ajax(Page_Load事件中)
protectedvoid Page_Load(object sender, EventArgs e){AjaxPro.Utility.RegisterTypeForAjax(typeof(CalendarServices)); //AjaxPro会根据注册的类型自动生成脚本}//d.在App_Code中的类库文件(cs文件中)编写带有Ajax标签的处理方法
using System;using System.Collections.Generic;using System.Linq;using System.Web;publicclass CalendarServices{[AjaxPro.AjaxMethod]publicbool save(string date, string tile, string detail){System.Threading.Thread.Sleep(5000); //用来测试异步returntrue; //这里为简单, 直接返回true}}//e.在前台的aspx文件中使用脚本处理结果(修改内存中的DOM对象)并显示在页面上
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"%><!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></head><body><form id="form1" runat="server"><div>日期:<input id="date" type="text"/><br />标题:<input id="title" type="text"/><br />详情:<textarea id="detail" cols="80" rows="5"></textarea><hr /><input id="btn" type="button" value="确定"/></div><div><script src="jquery-1.4.2.js" type="text/javascript"></script><script type="text/javascript">$(function() {$("#btn").click(function() {var date = $("#date").val();var title = $("#title").val();var detail = $("#detail").val();//由AjaxPro生成的js代理, 很像C#中类库的使用, 其中function(result)是异步的结果处理方法CalendarServices.save(date, title, detail, function(result) {if (result.error !=null) { //服务器上出现异常alert(result.error.Message);}if (result.value) { //服务器cs文件中的方法返回永真alert("服务器返回true! ");}});});});</script></div></form></body></html>2.2. 以前使用的老板Ajax(维护老项目可能用到, 其实与第2种很类似): a.引用Ajax框架类库 b. webconfig中添加配置 c.在App_Code中添加Ajax服务类, 并在CS文件中注册Ajax(Page_Load事件中) d.在App_Code中的CS文件中带Ajax标签的处理方法 e.按钮绑定触发JS的方法 f.JS处理方法
<httpHandlers><add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax"/></httpHandlers>//c. 在CS文件中注册Ajax(Page_Load事件中)
Ajax.Utility.RegisterTypeForAjax(typeof(SysBase_UserEdit)); //SysBase_UserEdit是页面文件名称//d. 在App_Code中的CS文件中带Ajax标签的处理方法
[Ajax.AjaxMethod]public DataSet getRoleData(int Roleid){DataSet ds =new DataSet();ds = r.SelectRoleData(string.Format(" and id={0}", Roleid));return ds;}//e. 按钮绑定触发JS的方法
this.DDLRole.Attributes.Add("onpropertychange", "onCommandInputPropertyChange();"); //在Page_Load事件中基于Attribute为按钮绑定方法, 在aspx文件中手动添加也可以//f. JS处理方法
<script> function onCommandInputPropertyChange(){ if (event.propertyName == "value"){ var cmdInput = event.srcElement; if (cmdInput.value != 0){ //alert(cmdInput.value); BindRoleName(cmdInput.value);} } } //绑定角色名 function BindRoleName(RoleID){ //SysBase_UserEdit是aspx页面的名称 SysBase_UserEdit.getRoleData(RoleID,get_AllName); } function get_AllName(response){ var AllName = document.getElementById("DDLAjax"); AllName.length = 0; if (response.value != null){ var ds = response.value; if(ds != null && typeof(ds) == "object"){var name = ds.Tables[0].Rows[0].rolename; var id = ds.Tables[0].Rows[0].id;AllName.options.add(new Option(name,id)); } } } </script>3. VS2008集成的Ajax:
<Triggers><asp:AsyncPostBackTrigger ControlID="AspNetPager1"/><asp:AsyncPostBackTrigger ControlID="btn_Search"/><asp:AsyncPostBackTrigger ControlID="btn_Delete"/></Triggers>//f. VS2005需要配置webConfig
<httpHandlers><!-- 调用AjaxPro.2--><add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro.2"/><remove verb="*" path="*.asmx"/><add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/><add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/><add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/></httpHandlers>============================分割线============================