티스토리 뷰

CS파일 메서드에서는 일반 텍스트스트링이 아닌 Collection 객체를 넘겨보도록 하겠다.

해당 메서드위에  [WebMethod] 를 꼭 선언 해주어야 ajax로 받을 수 있다.

[WebForm1.cs]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

namespace WebMethod_JSON
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static List<Person> GetContents(string name)
        {
            List<Person> li = new List<Person>();
            li.Add(new Person { Name = "홍길동", Name2 = "Hong" });
            li.Add(new Person { Name = "김길동", Name2 = "Kim" });
            li.Add(new Person { Name = "박길동", Name2 = "Park" });

            return li;
        }
    } 

    public class Person
    {
        public string Name { get; set; }
        public string Name2 { get; set; }
    }
}

[WebForm1.aspx]

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebMethod_JSON.WebForm1" %>

<!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">
    <script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
    <title></title>
    <script type="text/javascript">

        $(document).ready(function () {
            $("#click").click(function () {
                var txt_nm = $(this).val();

                if (txt_nm == "")
                    return false;
                else {
                    $.ajax({
                        type: "POST", // 데이터는 POST 형식으로 받을 것이고
                        url: "WebForm1.aspx/GetContents", // [WebMethod]로 선언한 GetContents 메서드를 불러들인다.
                        data: "{name:'" + txt_nm + "'}", // WebMeth로 선언한 GetContents에 인자값으로 txt_nm을 넘길 수 있다. 하지만 이번 예제는 Collection 객체를 가져오는걸 보기위해서. 인자값넘기는 메서드는 선언 안했다. 나중에 필요할때 이렇게 쓰면된다. name은 인자값 변수명이다.
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (msg) { // 성공하면

                            alert(msg.d[1].Name + "\n 현재시간은" + Date());  // 웹메서드에서 리턴한 Collection 객체는 msg.d[ ] array 형태로 받을 수 있다. jquery each를 이용해서 파싱을 하던. 그건 사용자가 마음대로. Name은 프로퍼티명이다.
                           
                        },
                        error: function (xhr, status, error) { alert(error + "\n" + status + "\n" + xhr); }
                    });
                }
            });
        });

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="testArea">
    <h2>Jquery를 이용한 ajax 통신 (JSON).</h2>
   
    <input type="button" id="click" value="호출" />
    <div id="result">
   
    </div>
</div>
    </form>
</body>
</html>

실행해서 호출 버튼을 누르면. 아래와 같은 결과를 얻을 수 있다.

김길동은 위에 Collection 에 첫번째 Name 프로퍼티의 값을 가져온것이고.

시간은뭐.. 현재시간 가져온거다.

 

 

당연한 이야기지만 호출을 계속 하면 시간은 변한다. 피들러로 찍어보면

이러한 결과를 받아볼 수 있다. 비주얼 스튜디오 내에서 로컬로 실행하면 피들러로 데이터를 찍어 볼 수 없다.

하지만 http://localhost:3242/WebForm1.aspx 란 주소에 . 점하나만 찍으면 피들러에서 확인 가능하다. 

WCF를 이용한다면 직접 WCF에 웹 메소드에 붙어서도 가져올 수 있고. 지금처럼 CS단에서 웹 메소드를 만들어 놓고 가져다가 써도된다. 사용하기 편한걸로 갔다가 쓰는게 좋지만. 개인적으로는 이게 더 편하다.

http://localhost.:3242/WebForm1.aspx

 

 

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함