为了账号安全,请及时绑定邮箱和手机立即绑定

jquery, json与ashx的完美结合

标签:
JQuery

第一部分:客户端页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApplication1.WebForm3" %>

<!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 class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="jquery-1.3.2-vsdoc.js" type="text/javascript"></script>

<script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="json2.js" type="text/javascript"></script>

<script type="text/javascript">
$(function() {
//构造一个json对象,很类似于C#中的匿名类型
var employee = {
Name: "chenxizhang",
Country: "China",
Orders: [
{ OrderID: 10248 },
{ OrderID: 10249 }
]
};

//发送POST请求,数据也是json格式。但数值部分需要转换为字符串
$.post("EmployeeHandler.ashx", { data: JSON.stringify(employee) }, function(result) {
var r = JSON.parse(result);
alert(r.Message);
});
});
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>

第二部分:ashx部分

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.IO;
using System.Text;
//必须添加System.ServiceModel.Web和System.Runtime.Serialization的引用
namespace WebApplication1
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class EmployeeHandler : IHttpHandler
{

public void Proce***equest(HttpContext context)
{
var ser = new DataContractJsonSerializer(typeof(Employee));
var data = context.Request["data"];
var ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
var emp = (Employee)ser.ReadObject(ms);
ms.Close();
//此时已经得到了相应的Employee实例,可以进行服务器端的处理

 


var ser2 = new DataContractJsonSerializer(typeof(ActionResult));
var ms2 = new MemoryStream();
var result = new ActionResult() { Code = 200, Message = "成功" };
ser2.WriteObject(ms2, result);
ms2.Position = 0;
var buffer = new byte[ms2.Length];
ms2.Read(buffer, 0, buffer.Length);
ms2.Close();
context.Response.Write(Encoding.UTF8.GetString(buffer));

//返回结果



}

public bool IsReusable
{
get
{
return false;
}
}
}

[DataContract]
public class Employee {
[DataMember]
public string Name { get; set; }

[DataMember]
public string Country { get; set; }

[DataMember]
public OrderItem[] Orders { get; set; }


}
[DataContract]
public class OrderItem
{
[DataMember]
public int OrderID { get; set; }
}

[DataContract]
public class ActionResult
{
[DataMember]
public int Code { get; set; }
[DataMember]
public string Message { get; set; }

}
}

第三部分:进一步的优化,编写两个扩展方法(这是C# 3.0的新特性) /// <summary>
/// 这个类型实现了对JSON数据处理的一些扩展方法
/// </summary>
public static class JsonExtensions
{
/// <summary>
/// 根据一个字符串,进行JSON的反序列化,转换为一个特定类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public static T ToJsonObject<T>(this string data) {
var serializer = new DataContractJsonSerializer(typeof(T));
var ms = new MemoryStream(
Encoding.UTF8.GetBytes(data));

var result = (T)serializer.ReadObject(ms);
ms.Close();
return result;
}
/// <summary>
/// 将任何一个对象转换为JSON字符串
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJsonString<T>(this T obj) {
var serializer = new DataContractJsonSerializer(typeof(T));
var ms = new MemoryStream();
serializer.WriteObject(ms, obj);
ms.Position = 0;
var result = Encoding.UTF8.GetString(ms.GetBuffer());
ms.Close();
return result;
}
} 这样,在ashx里面的代码就很简单了 var emp = context.Request["data"].ToJsonObject<Employee>();
var result = new ActionResult() { Code = 200, Message = "成功" };
context.Response.Write(result.ToJsonString());
不错吧,这样以后处理Json就是如此容易


通过Json来传递数据,可以避免以前用传统的post或者get方面拼接字符串中的麻烦

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消