您的位置:首页 > 其它

Ajax 调用后台方法

2012-08-27 15:28 232 查看
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>


 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息