您好,欢迎来到凯特情感。
搜索
您的当前位置:首页jQueryasp.net用json格式返回自定义对象_jquery

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

来源:凯特情感


客户端用一个html页面调用一个ashx文件(一般http处理程序),返回 json格式的自定义对象:
html:
代码如下:



ajax测试




$(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);
})
})
})

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



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()
{ }
}
}

Copyright © 2019- ktwm.cn 版权所有

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务