C#中jQuery Ajax实例(二)
上一篇写了一个简单的Ajax异步程序,这一次同样是简单的程序,只不过这次先把参数传到一般处理程序(后缀为ashx)中,再把结果传回到页面。
1.html代码:
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Ajax实例2</title> <script src="Scripts/jquery-1.7.1.min.js"></script> <script type="text/javascript"> $(function () { $("#btn2").click(function () { var params = {};//参数数组 params.action = "GetAjaxValue"; params.param1 = $("#txtParam1").val(); params.param2 = $("#txtParam2").val(); $.ajax({ url: "AjaxHandler.ashx",//指向一搬处理程序 data: params, type: "POST", async: true, //contentType: "application/json; charset=utf-8", dataType: "json", beforeSend: function () { //发送请求前执行 }, success: function (msg) { if (msg.OperateResult == "success") { if (msg.ResponseData.length > 0) { $("#result").html(msg.ResponseData); } } }, error: function (e) { alert("请求出错处理"); }, complete: function () { } }); }); }); </script> </head> <body> <form id="form1" runat="server"> 参数1:<input type="text" id="txtParam1" value="" /><br /> 参数2:<input type="text" id="txtParam2" value="" /><br /> <input type="button" id="btn2" value="提交"/><br /> <div id="result"></div> </form> </body> </html>
2.新建一般处理程序AjaxHandler.ashx,代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Serialization;//必须 namespace AjaxDemo { /// <summary> /// AjaxHandler 的摘要说明 /// </summary> public class AjaxHandler : IHttpHandler { private JavaScriptSerializer json = new JavaScriptSerializer(); private string operateSuccess = "success"; private string operateFailed = "false"; public void ProcessRequest(HttpContext context) { string jsonObject = string.Empty; string action = context.Request["action"]; //context.Response.ContentType = "text/plain";//服务端需要返回一段普通文本给客户端 context.Response.ContentType = "application/json;charset=utf-8";//服务端需要返回一段json串给客户端 if (action == "GetAjaxValue") { try { string param1 = context.Request["param1"]; string param2 = context.Request["param2"]; string result = "第一个参数:" + param1 + "第一个参数:" + param2; jsonObject = json.Serialize(new { OperateResult = operateSuccess, ResponseData = result }); } catch (Exception e) { jsonObject = json.Serialize(new { OperateResult = operateFailed, ResponseData = e.Message }); } } context.Response.Write(jsonObject); } public bool IsReusable { get { return false; } } } }
3.界面以及运行结果:
5.注意:
在第1步代码中,我注释了contentType: "application/json; charset=utf-8" 这句话,因为加了这句,程序会无法把参数params 传到一般处理程序中。