【转】JQuery ajax json 实例
序列化字符方法:注意这里的引用“System.Runtime.Serialization”和“System.ServiceModel.Web”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Web;///记得引用这个命名空间
using System.IO;
using System.Text;
namespace BLL
{
/// <summary>
/// 序列化实体类
/// </summary>
public class JsonHelper
{
public JsonHelper()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// 把对象序列化 JSON 字符串
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="obj">对象实体</param>
/// <returns>JSON字符串</returns>
public static string GetJson<T>(T obj)
{
//记住 添加引用 System.ServiceModel.Web
/**
* 如果不添加上面的引用,System.Runtime.Serialization.Json; Json是出不来的哦
* */
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
json.WriteObject(ms, obj);
string szJson = Encoding.UTF8.GetString(ms.ToArray());
return szJson;
}
}
/// <summary>
/// 把JSON字符串还原为对象
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="szJson">JSON字符串</param>
/// <returns>对象实体</returns>
public static T ParseFormJson<T>(string szJson)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
{
DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
return (T)dcj.ReadObject(ms);
}
}
}
}
实体类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Model
{
public class jsonItem
{
public string UserName { get; set; }
public string PWD { get; set; }
}
}
调用方法:用反射方式,只需传方法就可以执行
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Text;
namespace test.JQuery.json
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class json : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//反射的机制:只需要传方法进来就可以执行方法、获得数据。。
if (context.Request["cmd"] != null)
{
string cmd = context.Request["cmd"];
var method = this.GetType().GetMethod(cmd);
if (method != null)
{
method.Invoke(this, new object[] { context });
}
}
}
/// <summary>
/// 序列化的Json字符串
/// </summary>
public void GetInfo(HttpContext context)
{
Model.jsonItem item = new Model.jsonItem();
Model.jsonItem item1 = new Model.jsonItem();
List<Model.jsonItem> list = new List<Model.jsonItem>();
item.UserName = "aaaa";
item.PWD = "1111";
list.Add(item);
item1.UserName = "bbbb";
item1.PWD = "2222";
list.Add(item1);
string strJson = BLL.JsonHelper.GetJson<List<Model.jsonItem>>(list);
context.Response.Write(strJson);
}
/// <summary>
/// 序列化的Json字符串
/// </summary>
public void GetInfo1(HttpContext context)
{
Model.jsonItem item = new Model.jsonItem();
Model.jsonItem item1 = new Model.jsonItem();
List<Model.jsonItem> list = new List<Model.jsonItem>();
item.UserName = "abc";
item.PWD = "123";
list.Add(item);
item1.UserName = "bcd";
item1.PWD = "234";
list.Add(item1);
string strJson = BLL.JsonHelper.GetJson<List<Model.jsonItem>>(list);
context.Response.Write(strJson);
//string output = string.Format("'UserName':'{0}','PWD':'{1}'", "cccc", "3333");
//string output1 = string.Format("'UserName':'{0}','PWD':'{1}'", "dddd", "4444");
//StringBuilder result = new StringBuilder();
//result.AppendFormat("[{0}{1}{2},{3}{4}{5}]", "{", output, "}", "{", output1, "}");
//context.Response.Write(result.ToString());
//context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
html代码调用:
<!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="http://imwujianhao.blog.163.com/blog/../jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
function BtnClick() {
var uid = $("#Text1").val();
var pwd = $("#Text2").val();
$.ajax({
url: "json.ashx",
type: "POST",
data: { cmd: "GetInfo", Password: pwd },
beforeSend: loading,
success: function(data) {
var json = eval(data); //eval("(" + data + ")");
$("#dd").empty(); //清除dd的信息
$.each(json, function(idx, item) {
var user = item.UserName;
var pass = item.PWD;
$("#dd").append("<b>用户名:" + user + " 密码:" + pass + "</b>");
});
}
});
}
function loading() {
$("#dd").html("<img src='http://imwujianhao.blog.163.com/blog/20-0.gif' />");
}
function BtnClick1() {
$.ajax({
url: "json.ashx",
type: "POST",
data: { cmd: "GetInfo1" },
beforeSend: loading,
success: function(data) {
//使用eval函数
var json = eval(data);
$("#dd").empty();
//因为上面为list集合
for (var i = 0; i < json.length; i++) {
$("#dd").append("<h3>用户名:" + json[i].UserName + " 密码:" + json[i].PWD + "</h3>");
//alert(json[i].Id + "Name:" + json[i].Name);
}
}
});
}
</script>
</head>
<body>
<div>
<input type="text" name="Text1" id="Text1" /><br />
<input type="text" name="Text2" id="Text2" />
<br />
<input type="button" id="btn1" value="事件1" onclick="BtnClick()" />
<input type="button" id="Button1" value="事件2" onclick="BtnClick1()" />
</div>
<div id="dd">
sd
</div>
</body>
</html>
原文地址:http://imwujianhao.blog.163.com/blog/static/163776830201066115125616/