jQuery asp.net 用json格式返回自訂對象

來源:互聯網
上載者:User

用戶端用一個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#" 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()
{ }
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.