<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ASP.NETA_JAX.aspx.cs" Inherits="_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 type="text/jscript">
function CallServer() {
//JSON发送对象
ServerSum("{name:'linyijia',age:'21'}");
}
function GetRegister(rg, contex) {
document.getElementById("TxtRegister").value=rg;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
用户名:<input id="TxtNum1" type="text" />
<br />
服务器:<input id="TxtRegister" type="text" /><br />
<button id="SumBtn" type="button" onclick="CallServer()">登录</button>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
public partial class _Default : System.Web.UI.Page ,ICallbackEventHandler
{
Users u = null;
protected void Page_Load(object sender, EventArgs e)
{
//回调GetRegister方法
string CallBackFun = Page.ClientScript.GetCallbackEventReference(this,"arg","GetRegister","context");
//创建ServerSum方法,在客户端调用的时候就,会回调GetRegister方法,把参数传给RaiseCallbackEvent(string eventArgument ),最后通过
//GetCallbackResult()方法把返回值传给客户端
string RegisterFun = string.Format("function ServerSum(arg,context){{{0};}}",CallBackFun);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"ServerSum",RegisterFun,true);
}
string mssage = string.Empty;
#region ICallbackEventHandler 成员
public string GetCallbackResult()
{
return "服务器:你好,你的用户名为:" + u.Name + "你的年龄为" + u.Age;
}
public void RaiseCallbackEvent(string eventArgument)
{
JavaScriptSerializer js = new JavaScriptSerializer();
u =js.Deserialize<Users>(eventArgument);
}
#endregion
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
///User 的摘要说明
/// </summary>
public class Users
{
string name;
public string Name
{
get { return name; }
set { name = value; }
}
string age;
public string Age
{
get { return age; }
set { age = value; }
}
}
使用JSON向服务器发送一个对象,服务器通过实现 ICallbackEventHandler接口后,重写GetCallbackResult和RaiseCallbackEvent方法,在回调的时候,在RaiseCallbackEvent方法中反序列化JSON,并在GetCallbackResult把结果返回给客户端.
一.准备工作:
1.建web应用程序aspnetAjax
2.建index.htm
3.建个js文件夹,把jquery.js放进去,
4.建ajax文件夹,里面放ashx
5.在js文件夹建index.js,一般我们都是一个页面对应一个js
6.在ajax文件夹,建IndexHandler.ashx,一般一个js页面对应一个一般用户控件,这样层次感很强,也很好维护。
二.html页面
html页面就简单了,我们要用ajax读后台做个下拉列表,所以页面就放个DIV就行了。其他的交给js.
<!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>
<title>测试</title>
<script src="js/jquery-1.2.3-intellisense.js" type="text/javascript"></script>
<script src="js/index.js" type="text/javascript"></script>
</head>
<body>
企业性质<div id="vocaspec"> </div>
行业类型<div id="industr"> </div>
</body>
</html>
编写IndexHandler.ashx代码
namespace aspnetAjax.ajax
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
public class IndexHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
//接收提交过来的meth参数
string meth = context.Request.Params["meth"].ToString();
//根据参数调用不同的方法
switch (meth)
{
case "load":
loadjson(context);
break;
case "add":
add(context);
break;
}
}
public bool IsReusable
{
get
{
return false;
}
}
//页面加载方法,调用BLL,获得数据
private void loadjson(HttpContext context)
{
//实例BLL
VocaSpecSortBLL vocaSpec = new VocaSpecSortBLL();
BLL.Owner ownerbll = new GYXMGL.BLL.Owner();
DataSet ds = vocaSpec.GetList("");
DataSet dsindustr = ownerbll.Getcharcte();
//实例一个StringBuilder 用来拼接一个json数据
StringBuilder sbvoca = new StringBuilder();
if (ds != null && ds.Tables[0].Rows.Count > 0)
{
sbvoca.Append("{\"voce\":[");
int i = 1;
int count = ds.Tables[0].Rows.Count;
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (i == count)
{
sbvoca.Append("{\"code\":\"" + dr[0] + "\",\"name\":\"" + dr[1] + "\"}");
}
else
{
sbvoca.Append("{\"code\":\"" + dr[0] + "\",\"name\":\"" + dr[1] + "\"},");
}
i++;
}
sbvoca.Append("]");
}
if (dsindustr != null && dsindustr.Tables[0].Rows.Count > 0)
{
sbvoca.Append(",\"industr\":[");
int i = 1;
int count = dsindustr.Tables[0].Rows.Count;
foreach (DataRow dr in dsindustr.Tables[0].Rows)
{
if (i == count)
{
sbvoca.Append("{\"code\":\"" + dr[0] + "\",\"name\":\"" + dr[1] + "\"}");
}
else
{
sbvoca.Append("{\"code\":\"" + dr[0] + "\",\"name\":\"" + dr[1] + "\"},");
}
i++;
}
sbvoca.Append("]");
}
sbvoca.Append("}");
context.Response.Write(sbvoca.ToString());
context.Response.End();
}
}
}
我们把index.js改下
$(document).ready(function() {
$.ajax({
type: "POST",
url: "../ajax/NewOwnerHandler.ashx",
//我们用text格式接收
dataType: "text",
data: "meth=load",
success: function(msg) {
alert(msg);
//显示后台数据
$("#vocaspec").html(msg);
// $("#industr").html(industr);
}
});
});
看到如下数据,就是ashx中response给我们的json格式数据,现在我们要把这些数据
显示在下拉列表中。就要遍历json中的数组。
{
"voce":[{"code":"1","name":"农林水利"},{"code":"10","name":"军工"},{"code":"11","name":"农林"},{"code":"12","name":"水利(电)"},{"code":"13","name":"水电站"},{"code":"14","name":"输变线"},{"code":"15","name":"煤矿"},{"code":"16","name":"气田"},{"code":"17","name":"公路"},{"code":"18","name":"铁路"},{"code":"19","name":"民航"},{"code":"2","name":"能源"},{"code":"20","name":"信息产业"},{"code":"21","name":"化工"},{"code":"22","name":"机械"},{"code":"23","name":"冶金"},{"code":"24","name":"有色金属"},{"code":"25","name":"建材"},{"code":"26","name":"医药"},{"code":"27","name":"轻工"},{"code":"28","name":"农牧产品深加工"},{"code":"3","name":"交通"},{"code":"4","name":"通讯"},{"code":"5","name":"特色产业"},{"code":"6","name":"城市基础设施"},{"code":"7","name":"商贸流通"},{"code":"8","name":"旅游"},{"code":"9","name":"文体卫"}],
"industr":[{"code":"1","name":"国有"},{"code":"2","name":"私人"}]
}
修改index.js代码,遍历json数据把数据显示成下拉列表
$(document).ready(function() {
$.ajax({
type: "POST",
url: "../ajax/NewOwnerHandler.ashx",
//json格式接收数据
dataType: "json",
//指点后台调用什么方法
data: "meth=load",
success: function(msg) {
//实例2个字符串变量来拼接下拉列表
var industr = "<select name=\"industr\"><option label=\"---请选择---\"></option>";
var vocaspec = "<select name=\"vocaspec\"><option label=\"---请选择---\"></option>";
//使用jquery解析json中的数据
$.each(msg.voce, function(n, value) {
vocaspec += ("<option value=\"" + value.code + "\" label=\"" + value.name + "\">");
vocaspec += ("</option>");
});
$.each(msg.industr, function(n, value) {
industr += ("<option value=\"" + value.code + "\" label=\"" + value.name + "\">");
industr += ("</option>");
});
industr += ("</select>");
$("#vocaspec").html(vocaspec);
$("#industr").html(industr);
}
});
});
这个实例涉及到的知识点
1.使用一般处理程序,接收request。并可以使用response数据
string meth = context.Request.Params["meth"].ToString();
因为一般处理程序
public class IndexHandler : IHttpHandler
他实现IHttpHandler接口
2.json数据格式
3.使用jquery ajax,并用jquery解析json数据。