欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

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

程序员文章站 2022-05-31 16:01:19
...
客户端用一个html页面调用一个ashx文件(一般http处理程序),返回 json格式的自定义对象:
html:
复制代码 代码如下:




ajax测试




姓名:type="text" />年龄:
type="text" />



handler.ashx文件:
复制代码 代码如下:


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()
{ }
}
}
相关标签: jQuery json格式