관리 메뉴

IT 쟁이

2-1 XMLHttpRequest 객체 예제 본문

카테고리 없음

2-1 XMLHttpRequest 객체 예제

클라인STR 2008. 1. 22. 02:45

저는 jsp를 조금 밖에 공부안해봐서 그런지 이책의 예제는 잘이해가 안되더군요.그래서 .NET에서 돌아가게끔 몇가지 부분을 바꿔서 만들었습니다. 책에서는 httpRequest.js파일을 모두 참조하여 했었는데..아무래도
.NET에서는 이상하게 형식이 일치하지 않는다는 오류가 나서 .js파일 도 수정하였습니다.

Default.aspx

<%@ 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">
<meta http-equiv="Content-Type"  content="text/html; charset=euc-kr;"  />
    <title>제목 없음</title>
 
    <script type="text/javascript">
    function getXMLHttpRequest() {
 if (window.ActiveXObject) {
  try {
   return new ActiveXObject("Msxml2.XMLHTTP");
  } catch(e) {
   try {
    return new ActiveXObject("Microsoft.XMLHTTP");
   } catch(e1) { return null; }
  }
 } else if (window.XMLHttpRequest) {
  return new XMLHttpRequest();
 } else {
  return null;
 }
}
    var httpRequest = null;
   
     function helloToServer()
    {
        var pageurl ="Default2.aspx?name="+ document.forms[0]['TextBox1'].value;
       
         httpRequest = getXMLHttpRequest();  //크로스 브라우저 문제
        httpRequest.open("POST", pageurl, true);
        httpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        httpRequest.onreadystatechange = helloFromServer; //콜백함수 지정
        httpRequest.send(null);
           
       
    }
   
    function helloFromServer()
    {
        if(httpRequest.readyState == 4)
        {
            if(httpRequest.status == 200)
            {
                alert(httpRequest.responseText);
            }
        }
       
    }
   
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><input id="Button1" type="button" value="열림"  onclick="helloToServer();" />&nbsp;
      
       
    </form>
</body>
</html>

Default2.aspx 생성하고 다음과 같이 코딩하였다.
protected void Page_Load(object sender, EventArgs e)
    {
        string id = Request.QueryString["name"].ToString();

        if (Request.QueryString["name"] != null)
        {
            Response.Write(id);
          
        }
     
        Response.End();
    }

웹페이지를 생성하면 다음과 같이 된다.

사용자 삽입 이미지



사용자 삽입 이미지


한글처리문제를 해주지 않기때문에 -_-이런일이 발생합니다. 이럴땐  web.config 다음과 같은 설정을 추가합니다.
 <globalization requestEncoding="ks_c_5601-1987" responseEncoding="ks_c_5601-1987"/>
또는
 <globalization requestEncoding="euc-kr" responseEncoding="euc-kr"/>

정상적으로 출력되는것을 알 수 있다.
사용자 삽입 이미지



다음과 같은 메시지가 발생할 경우는 -_- 서버쪽코드 에서 Response.End()메서드가 빠져있는지 꼭 확인을 해야된다.

사용자 삽입 이미지

-ㅇ- 오늘도 오랜만에 Ajax코딩을하다보니 몇시간은 해맺던거 같다. 조심하길!!!!!
Comments