AJAx 具体案例。

1.在项目中添加此dll的应用,同时需要在 webconfig的 <system.web> 里面 加上

<httpHandlers>
  <add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory,Ajax"></add>
</httpHandlers>

2.在应用页面的Page_Load中添加
Ajax.Utility.RegisterTypeForAjax(typeof(页面名));

3.在要调用的后台方法前加ajax的声明

①操作session时
  [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.Read)]
  public void GetBranchSelectIndex(int selectIndex)
  {
  Session["BranchSelIndex"] =selectIndex;
  }

②其他操作的时候
  [Ajax.AjaxMethod()]
  public DataTable DependLineGetBranch(string strLineCD)
  {
  clsMainDB mdbBranch = new clsMainDB();
  dtBranchInfo = mdbBranch.GetBreadBranchInfo(strLineCD);
  int i=dtBranchInfo.Rows.Count;
  return dtBranchInfo;
  }

4.在前台的js中写function中调用此方法
 var abc=页面名.方法名(参数).value;//有返回值
页面名.方法名(参数);//没有返回值


③注意点
(1).不可以读取 cookie的值,但是可读session的值 不能使用Request去参数值,不能使用控件名字
(2)方法中不能出现后台的控件,比如 this.xxxx 会提示[未定义]
(3)不能调用重载方法,如果重载方法将调用失败。

案例代码如下

前台代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxExample.aspx.cs" Inherits="AjaxExample" %>
<!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>
    function AClick()
    {
         alert('The AjaxMethod start ');
         var msg= AjaxExample.WriteText().value;
         alert(msg);
         alert('The AjaxMethod end ');
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <a href="javascript: AClick();">请点击这里</a>
    <asp:Literal ID="ltrTree" runat="server"></asp:Literal>
    </div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>
</body>
</html>

后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class AjaxExample : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Ajax.Utility.RegisterTypeForAjax(typeof(AjaxExample),Page);
    }
    [Ajax.AjaxMethod()]
    public string WriteText()
    {
        //ChangeLabel();
        //Response.Write("ok");
        //return Request["str"];
        //Page.RegisterStartupScript("", "<script>alert('2');</script>");
        return "后台方法成功调用!";
    }
    public void ChangeLabel()
    {
        Label1.Text = "abcdef";
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值