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