[ResponseText.aspx.cs]



using System;

using System.Web.Services;

using System.Collections.Generic;

using System.Web.Script.Services;

 

public partial class Ajax_AspNet_ResponseText : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        // Empty

    }

 

    // List<T> 형태를 JSON 형태로 출력

    [WebMethod]

    [ScriptMethod(ResponseFormat=ResponseFormat.Json)]

    public static List<Memo> GetMemos()

    {

        List<Memo> lst = new List<Memo>() {

            new Memo(){Num=1,Name="홍길동"},

            new Memo(){Num=2,Name="백두산"},

            new Memo(){Num=3,Name="한라산"}

        };

        return lst;

    }

}

 

public class Memo

{

    public int Num { get; set; }

    public string Name { get; set; }

}

 

 



-------------------------------------------------------------------------------------




[04.ListToJSON.htm]




<!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>리스트값 반환</title>

    <script src="../../js/jquery-1.3.2-vsdoc2.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function () {

            $.ajax({

                type: "post",

                url: "ResponseText.aspx/GetMemos",

                data: "{}",

                contentType: "application/json; charset=utf-8",

                dataType: "json",

                success:displayData, // displayData함수로 외부에 출력코드 작성

                error: function (data) { alert('에러 발생'); }

            });

        });

        function displayData(data, status) {

            $('#ctlMemoList').empty();

            var table = "<table><tr><td>번호</td><td>이름</td></tr>";

            // Microsoft Ajax에서는 보안목적으로 data.d로 실제 데이터를 감싸놓음.

            $.each(data.d, function (index, entry) {

                table += '<tr><td>' + entry["Num"] + '</td><td>' + entry["Name"] + '</td></tr>';

            });

            table += "</table>";

            $('#ctlMemoList').append(table);

        }

    </script>

</head>

<body>

    <div id="ctlMemoList"></div>

</body>

</html>

 




-------------------------------------------------------------------------------------




[실행결과]








Posted by holland14
: