jQuery asp.net 用json格式返回自定义对象_Javascript教程-查字典教程网
jQuery asp.net 用json格式返回自定义对象
jQuery asp.net 用json格式返回自定义对象
发布时间:2016-12-30 来源:查字典编辑
摘要:客户端用一个html页面调用一个ashx文件(一般http处理程序),返回json格式的自定义对象:html:复制代码代码如下:ajax测试...

客户端用一个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="js/jquery-1.2.3.js" type="text/javascript"></script><!-这里引用了jQuery框架->

</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#" %>

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

{ }

}

}

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新Javascript教程学习
    热门Javascript教程学习
    编程开发子分类