Ajax 调用后台方法

来源:互联网 发布:苏州市信鸽网络 编辑:程序博客网 时间:2024/05/22 04:43
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services;namespace FeiMiao.UI.Ajax{    /// <summary>    /// AjaxPostHandlers 的摘要说明    /// </summary>    [WebService(Namespace = "http://tempuri.org/")]    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]    public class Post : IHttpHandler    {        HttpContext httpContext;        public void ProcessRequest(HttpContext context)        {            httpContext = context;            context.Response.ContentType = "text/plain";            switch (getFormString("method"))            {                case "HelloWorld":                    HelloWorld();                    break;                case "Hello":                    Hello();                    break;            }        }        private void Hello()        {            string input = getFormString("input");            httpContext.Response.Write("你传入的参数:" + input);        }        private void HelloWorld()        {            httpContext.Response.Write("HelloWorldTest");        }        public bool IsReusable        {            get            {                return false;            }        }        public string getFormString(string key)        {            string s = HttpContext.Current.Request.Form[key];            return s == null ? "" : s;        }    }}

 

 

 

前台:

 

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="FeiMiao.UI.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>    <script src="Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>    <script type="text/javascript" language="javascript">        function Hello() {            $.post("Ajax/Post.ashx", { method: "HelloWorld" }, function (data) {                if (null != data && data != "") {                    alert(data);                }            }, "text");        }        function Test() {            $.post("Ajax/Post.ashx", { method: "Hello", input: "heihei" }, function (data) {                if (null != data && data != "") {                    alert(data);                }            }, "text");        }    </script></head><body>    <form id="form1" runat="server">    <div>        <input type="button" value="不带参数" onclick="Hello()" />        <input type="button" value="带参数" onclick="Test()" />        <asp:Button ID="btnTest" runat="server" OnClick="btnTest_Click" Text="Button" />        <br />    </div>    </form></body></html>