---Demo.aspx 页面
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
//页面调用Ajax
function InvokingAjax(url, data, sucessFunction) {
$.ajax({
type: "POST",
url: url,
async: true, //同步
dataType: "json",
data: { SEND_JSON: data },
//后台执行完成后,返回页面处理函数
success: sucessFunction
});
}
//查询
function Query() {
var tUserID = $("#txtUserID").val();
var tUserName = $("#txtName").val();
//参数名称区分大小写
var SEND_JSON = '{type:"QueryUser",userName: "' + tUserName + '", userID: "' + tUserID + '" }';
//调用Ajax
InvokingAjax("Handler1.ashx", SEND_JSON, successedFun);
}
//页面处理函数
function successedFun(data) {
if (data.error != undefined) {
alert('Error:' + data.error);
}
else {
$("#txtAge").val(data.age);
$("#txtRole").val(data.role);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="div1">
工号:<input type ="text" id="txtUserID" />
姓名:<input type="text" id="txtName" />
年龄:<input type="text" id="txtAge" disabled="disabled"/>
角色:<input type="text" id="txtRole" disabled="disabled"/>
<input type="button" οnclick="Query()" value="Query"/>
</div>
</form>
</body>
</html>
---代码处理程序Handler1.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq; //下载Newtonsoft.Json.dll,添加引用
namespace WebApplication
{
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Dictionary<string, string> returnValue = new Dictionary<string, string>();
JObject json = JObject.Parse(context.Request["SEND_JSON"]);
try
{
switch (json["type"].ToString())
{
case "QueryUser":
returnValue = QueryUser(json);
break;
}
}
catch (Exception er)
{
returnValue.Add("error", er.Message);
}
JavaScriptSerializer jss = new JavaScriptSerializer();
context.Response.ContentType = "text/plain";
context.Response.Write(jss.Serialize(returnValue));
}
private Dictionary<string, string> QueryUser(JObject json)
{
//下面一句代码抛出错误,检测Demo.aspx页面错误处理代码
//throw new Exception("执行报错!");
Dictionary<string, string> dict = null;
string username = json["userName"].ToString();
string UserID = json["userID"].ToString();
dict = new Dictionary<string, string>();
dict.Add("role", "Admin");
dict.Add("age", "24");
return dict;
}
public bool IsReusable
{
get
{
return false;
}
}
}