jQuery asp.net 用json格式返回自定义对象

(编辑:jimmy 日期: 2024/10/10 浏览:2)

客户端用一个html页面调用一个ashx文件(一般http处理程序),返回 json格式的自定义对象:
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>ajax测试</title>
<script src="/UploadFiles/2021-04-02/jquery-1.2.3.js"></head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$("#Button2").click(function(){
var url="handler.ashx?&name="+$("#Text1").val()+"&age="+$("#Text2").val();
$.get(url,function(result){
var obj=eval("("+result+")");
alert("姓名:"+obj.Name+"\n"+"年龄:"+obj.Age);
})
})
})
</script>
<input id="Button2" type="button" value="button" /><span lang="zh-cn">姓名:</span><input id="Text1"
type="text" /><span lang="zh-cn">年龄:</span>
<input id="Text2"
type="text" />
</body>
</html>

handler.ashx文件:
复制代码 代码如下:
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Runtime.Serialization.Json;
using System.Collections;
using System.Runtime.Serialization;
public class Handler : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string name = context.Request.Params["name"].ToString();
string age = context.Request.Params["age"].ToString();
person p1 = new person(name,age);
DataContractJsonSerializer djson = new DataContractJsonSerializer(p1.GetType());//将对象序列化为 JavaScript 对象表示法 (JSON)
djson.WriteObject(context.Response.OutputStream, p1);
}
public bool IsReusable {
get {
return false;
}
}
[DataContract]//要序列化,一定要加这个属性
public class person
{
[DataMember]//属性“DataMember”只在“property, indexer, field”声明中有效。
public string Name="无名士";
[DataMember]
public string Age="0";
public override string ToString()
{
return "姓名:" + Name + "年龄:" + Age;
}
public person(string name,string age)//自定义类person
{
this.Name = name;
this.Age = age;
}
public person()
{ }
}
}
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。