posted by 방랑군 2012. 1. 4. 03:12
출처 : http://yyman.tistory.com/232

오늘 새벽에 올린 '[ASP.NET] 웹 서비스 구현 하기(Ajax) - Javascript로 호출 - Hello World'에 이어서 JQuery(JSON)을 이용하여 데이터를 가져오는 방법에 대해 소개하겠습니다.

[보충 자료]

그 전에 앞서 이전에 소개해드린 강좌에서 빠진 내용을 하나 소개하겠습니다.
매개 변수입니다.

function chHelloWorld2() {
WebApplication1.WebService1.HelloWorld2($get("txtName").value, OnSuccess);
}

이 부분에서 $get("txtName").value, OnSuccess가 있습니다.

Web Service에서 실제로 구현된 코드는 아래와 같습니다.

[WebMethod]
public string HelloWorld2(string s1)
{
return "Hello World" + s1;
}

자바 스크립트 부분을 보충하자면 아래와 같이 정의할 수 있겠습니다.
네임스페이스.클래스.함수(매개 변수1, 매개 변수2, …, 매개 변수n, OnSuccess, OnFailure)
(Parameters: ControlId,Method name,Parameter1,Parameter2...n,CallbackMethod)



두 개의 입력을 받아서 출력하려면 웹 서비스를 다음과 같이 수정할 수 있습니다.

[WebMethod]
public string HelloWorld2(string s1, string2)
{
return "Hello World" + s1;
}

물론 클라이언트 부분에서도 수정해줘야 합니다.
Input(HTML 사용자 컨트롤)이 txtName1, txtName2라고 가정합니다.

function chHelloWorld2() {
WebApplication1.WebService1.HelloWorld2($get("txtName1").value, $get("txtName2").value, OnSuccess);
}



본론) JSON을 이용한 데이터 받기



위의 예제처럼 Alert을 이용하여 출력하는 예제입니다.

1. 솔루션 구성



WebService1.asmx과 index.aspx은 Visual Studio에서 생성할 수 있지만, 나머지 이상한 파일들은 별도로 내려받아야 합니다.


Jquery 홈페이지(http://www.jquery.com)에서 내려받으실 수 있습니다. 귀찮으신 분들은 첨부된 파일을 내려받으시면 됩니다.

2. WebService1.asmx 설정 하기

[WebService1.asmx.cs]


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace WebApplication1
{
/// <summary>
/// WebService1의 요약 설명입니다.
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// ASP.NET AJAX를 사용하여 스크립트에서 이 웹 서비스를 호출하려면 다음 줄의 주석 처리를 제거합니다.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld3(string s1, string s2)
{
return s1 + " " + s2;
}
}
}


[WebService1.asmx]

<%@ WebService Language="C#" CodeBehind="WebService1.asmx.cs" Class="WebApplication1.WebService1" %>

3. Index.aspx 파일 설정 하기

[index.aspx]


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="WebApplication1.index" %>
<!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-1.4.4.min.js" type="text/javascript">
</script>
<script src="js/jquery-ui-1.8.8.custom.min.js" type="text/javascript">
</script>

<script language="javascript" type="text/javascript">
function HelloQuery() {
$.ajax({
type: "POST",
url: "
http://localhost:50000/WebService1.asmx/HelloWorld3",
data: '{"s1":"' + $get("txtName1").value + '", "s2":"' + $get("txtName2").value + '"}',
processData: false,
contentType: "Application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input name="txtName1" id="txtName1" type="text" />
<input name="txtName2" id="txtName2" type="text" />
<a href="#" onclick="HelloQuery()">TEST</a>
</div>
<asp:ScriptManager runat="server">
<Services>
<asp:ServiceReference Path="~/WebService1.asmx" />
</Services>
</asp:ScriptManager>
</form>
</body>
</html>

http://localhost:50000/WebService1.asmx/HelloWorld3

선언된 파일의 주소를 모르시면 본인이 만드신 ASMX파일을 접속하셔서 확인하셔도 됩니다.

* 구문 확대해서 살펴보기

data: '{"s1":"' + $get("txtName1").value + '", "s2":"' + $get("txtName2").value + '"}',


data : ' { " 매개변수1 " : " ' + $get("클라이언트 input name 값").value + ' " ,
" 매개변수2 " : " ' + $get("클라이언트 input name 값").value + ' " ,


" 매개변수n " : " ' + $get("클라이언트 input name 값").value + ' " } '


ex) 매개 변수가 하나일 때

data:'{"s1":"' + $get("클라이언트 input name 값").value + '"}'



사용자 환경에 맞게 적절히 연구하시어 잘 사용하시기 바라는 마음으로 글을 정리해봅니다.
글을 정리하면서 느낀 것은 Visual Studio.NET에 맞게 설계된 것과 공개 소스에 맞게 설계된 것의 차이는 엄청난 자본의 투입으로 말미암아 편리한 것이지만, 한 소프트웨어 환경에서 구현해야만 하는 불편한 점이 있습니다.
이식성은 Jquery 아저씨가 확실히 좋습니다.
아무쪼록 Jquery를 활용하는 것과 웹 서비스의 Hello World 강좌를 이것으로 정리합니다.



참고 자료) http://alexandershapovalov.com/how-to-call-wcf-services-from-javascript-jquery-and-aspnet-ajax-39/