[jQuery] 前端利用jQuery傳送json格式的資料,後端用ashx來接收

  • 18710
  • 0
  • 2012-12-27

摘要:[jQuery] 前端利用jQuery傳送json格式的資料,後端用ashx來接收

最近碰到了一個需求要使用jQuery來post資料到Server端,且接收資料的方式要透過ashx然後反序列化所接收的資料至自訂型別,透過以下範例簡單說明。

首先我們先看一下專案的目錄結構:

  1. jquery.js:要記得先抓好jquery供後續引用
  2. Handler.ashx:這是後端程式用來接收並處理前端所傳過來的資料
  3. Default.aspx:這是前端用ajax發送資料

 

在Default.aspx裡面,我們會透過javascript建立兩個物件,分別有Name和Age的屬性,再透過Array的方式,將這兩個物件塞到Array裡面去。使用Ajax內建的$.ajax API,我們可以把url,type,data,sucess等幾個屬性先設定好,其中要注意到當我們想透過json格式來傳遞資料的時候,我們可以用JSON.stringify的方法來把想要傳送的陣列資料先轉換成json格式。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
    <title></title>
    <script src="js/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#Button1").click(function () {
                var person1 = new Object();
                person1.Name = "Superman";
                person1.Age = 29;

                var person2 = new Object();
                person2.Name = "Batman";
                person2.Age = 29;

                var array = [];
                array.push(person1);
                array.push(person2);
                
                $.ajax({
                    url: "webservice/Handler.ashx",
                    type: "post",
                    data: JSON.stringify(array),
                    success: function (data) {
                        document.write(data);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="Button1" type="button" value="button" />
    </div>
    </form>
</body>
</html>

 

再來看一下後端是如何透過ashx來接收前端傳送過來的json格式資料:

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.IO;

public class Handler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        string json = string.Empty;
        string message = string.Empty;
        bool result = false;

        using (var reader = new StreamReader(context.Request.InputStream))
        {
            json = reader.ReadToEnd();
        }
        
        if (!string.IsNullOrEmpty(json))
        {
            var personList = new JavaScriptSerializer().Deserialize>(json);
            
            foreach (Person p in personList)
            {
                result = true;
                message += p.Name + ":" + p.Age;
            }
        }

        this.SendResponse(context, result, message);
    }

    private void SendResponse(HttpContext context, bool result, string message)
    {
        context.Response.Write(new JavaScriptSerializer().Serialize(
            new
            {
                Result = result,
                Message = message
            }));
        
        context.Response.End();
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

要從後端接收前端所傳送過來的資料我們可以使用context.Request.InputStream的這個Stream物件,接著我們使用跟前端定義好的Person這個容器來當載體,將ashx所接收到的資料用JavaScriptSerializer提供的方法做反序列化的動作,接下來後端就可以利用反序列化所得到的資料集合再做後續的邏輯或是資料處理了。這邊要注意當前後端需要先協調好ajax傳送物件資料的屬性要和後端在反序列化所使用的自訂型別命名要一致,才不會發生前端明明有傳送資料但是後端再做反序列化後,資料集合裡面沒有任何物件的情形。