DIV CSS 佈局教程網

jQuery + ASP.NET:用 ashx 一般 HTTP 處理常式回傳 JSON 物件
編輯:JQuery特效代碼     

需要一個輕量、不必牽涉 ViewState 與頁面生命週期的回應端點時,.ashx 檔是最乾淨的選擇。以下示範前端用 jQuery 帶參數呼叫,後端序列化成 JSON 回傳。

前端 html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>ajax 測試</title>
<script src="js/jquery-1.2.3.js" type="text/javascript"></script>
</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.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);

        // 將物件序列化為 JSON
        DataContractJsonSerializer djson =
            new DataContractJsonSerializer(p1.GetType());
        djson.WriteObject(context.Response.OutputStream, p1);
    }

    public bool IsReusable { get { return false; } }

    // 要序列化一定要加 DataContract
    [DataContract]
    public class person
    {
        [DataMember] public string Name = "無名士";
        [DataMember] public string Age  = "0";

        public override string ToString()
        {
            return "姓名:" + Name + "年齡:" + Age;
        }

        public person(string name, string age)
        {
            this.Name = name;
            this.Age = age;
        }

        public person() { }
    }
}

三個實務上的建議

  • 別用 eval 解析 JSON。 改用 dataType: 'json' 讓 jQuery 自動解析,或呼叫 JSON.parse(),可避免執行任意程式碼的風險。
  • Content-Type 要正確。 回傳 JSON 時設為 application/json,並搭配 context.Response.ContentEncoding = Encoding.UTF8,中文才不會亂碼。
  • 中文參數要編碼。 前端可用 encodeURIComponent(),後端用 HttpUtility.UrlDecode() 還原,比直接拼接查詢字串安全。

另外,DataMember 只能套用在 property、indexer 或 field 上;若希望 JSON 欄位名稱與 C# 屬性不同,可改用 DataMember(Name = "...") 明確指定。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved