본문 바로가기

   
Programming/Ajax

Ajax객체 실행

반응형

//ajax.js

 

var myAjax; //전역변수

 

function CreateAjax() {

       //브라우저마다 ajax 객체 생성 방법이 상이

 

       if (typeof (ActiveXObject) == "function") {

             //ie6..예전 브라우저

             return new ActiveXObject("Microsoft.XMLHttp");

       }

       else if (typeof (XMLHttpRequest) == "function" || typeof (XMLHttpRequest) == "object") {

             //넷스케이프, ie최신

             return new XMLHttpRequest();

       }

       else {

             alert("브라우저가 Ajax를 지원하지 않습니다.");

             return null;

       }

}

 

페이지 전환없이 시간을 서버에 요청하여 계속 출력 됨.

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

 

<!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>

       <style type="text/css">

             #Button1

             {

                    width: 223px;

             }

       </style>

 

       <script src="ajax.js" type="text/javascript"></script>

       <script language="javascript" type="text/javascript">

// <![CDATA[

 

             function Button1_onclick() {

                    //1. ajax 객체 생성

                    myAjax = CreateAjax();

 

                    //2. 연결 설정(ajax객체가 서버의 어떤 페이지에게 데이터를 요청할지 설정)

                    //  (Method, URL, Async)

                    myAjax.open("GET", "Ex04Ok.aspx?dummy=" + new Date().getFullYear() + new Date().getMonth() + new Date().getDate() + new Date().getHours() + new Date().getMinutes() + new Date().getSeconds() + new Date().getMilliseconds(), true);

 

                    //3. 응답 이벤트 추가(데이터를 수신하는 순간 특정 이벤트 발생 -> 그 이벤트안에서 데이터를 받은 후 처리)

                    myAjax.onreadystatechange = GetData;

 

                    //4. 실행

                    // - 데이터 요청(+ 데이터 전송) -> 대화시도(데이터 주고 받음)

                    myAjax.send("");

             }

 

             function GetData() {

 

                    //if문 필수

                    if (myAjax.readyState == 4 && myAjax.status == 200) {

                           //응답받은 데이터?

                           var data = myAjax.responseText;

 

                           document.getElementById("Label1").innerText = data;        

                    }

             }

 

// ]]>

       </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

   

       <h2>

                    Ex04.aspx</h2>

             <h2>

                    <br />

                    Ajax<br />

                    <br />

&nbsp;- 자바스크립트의 ajax 객체(XMLHttpRequest)<br />

&nbsp;- 소켓(Socket)을 사용해서 브라우저와 서버간에 데이터 교환(페이지 새로 고침)<br />

                    <br />

                    <br />

                    Ajax 구현 준비물<br />

                    <br />

&nbsp;1. 데이터를 요청하는 페이지(Ajax 구현) : A.aspx&nbsp; -&gt; Ex04.aspx<br />

&nbsp;2. 데이터를 응답하는 페이지 : B.aspx&nbsp; -&gt; Ex04Ok.aspx<br />

                    <br />

                    <br />

                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

                    <br />

                    <br />

                    <input id="Button1" style="font-size: large; font-weight: bold" type="button"

                           value="현재 시간 출력하기" onclick="return Button1_onclick()" /><br />

                    <br />

                    <br />

                    <br />

                    <br />

                    <br />

                    <br />

             </h2>

             <br />

             <br />

             <br />

             <br />

             <br />

   

    </div>

    </form>

</body>

</html>

 





using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

             //이 페이지는 화면상에 출력하기 위한 용도X

             //ajax객체가 이 페이지를 요청하면 되돌려줄(응답) 데이터를 생성하는 페이지O

 

             //응답하는 데이터의 종류..

             // 1. text

             // 2. xml / html

             // 3. json

             // ...

 

 

             //웹페이지 반환x

             Response.ContentType = "text/plain";//txt MIME

 

             //직접 출력스트림(임시페이지)에 돌려줄 데이터를 기록

             Response.Write("현재 시간 : " + DateTime.Now.ToString());

 

             //종료(Render X)

             Response.End();

    }

}

 








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

 

<!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="ajax.js" type="text/javascript"></script>

       <script type="text/javascript">

             function Init() {

                    document.getElementById("TextBox1").onchange = IDCheck;

             }

 

             function IDCheck() {

                    //1. ajax 객체

                    myAjax = CreateAjax();

                    //2. 연결 설정

                    myAjax.open("GET", "Ex05Ok.aspx?id=" + document.getElementById("TextBox1").value, true);

                    //3. 받을 데이터 -> 이벤트 등록

                    myAjax.onreadystatechange = GetData;

                    //4. 전송

                    myAjax.send("");

             }

 

             function GetData() {

                    if (myAjax.readyState == 4 && myAjax.status == 200)

                    {

                           var result = myAjax.responseText;

                           if (result == "1")

                                 document.getElementById("Label1").innerText = "사용 가능한 아이디.";

                           else

                                 document.getElementById("Label1").innerText = "사용 불가능한 아이디.";

                    }

             }

       </script>

 

</head>

<body onload="Init();">

    <form id="form1" runat="server">

    <div>

   

       <h2>

                    Ex05.aspx</h2>

             <h2>

                    <br />

                    아이디 중복 검사 :

                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

&nbsp;<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

             </h2>

             <br />

             <br />

             <br />

             <br />

   

    </div>

    </form>

</body>

</html>

 

 

 

 

보낸 결과값을 처리하는 페이지

Ex05Ok.aspx

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

             //Ex05Ok.aspx?id=hong

 

             //DB

             string[] member = { "test", "hong", "admin" };

 

             bool result = true;

 

             foreach (string item in member)

             {

                    if (item == Request.QueryString["id"])

                    {

                           //중복 아이디 발견!!

                           result = false;

                           break;

                    }

             }

 

            

             //result?

             Response.ContentType = "text/plain";

             Response.Write(result ? "1" : "0");

             Response.End();

    }

}

 

 

 

 




Ex06.aspx

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

 

<!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>

 

       <style type="text/css">

             body, p, div, span, input, a

             {

                    font-size:12px;

             }

            

             #TextBox1

             {

                    border:7px solid lightgreen;

                    width:300px;

             }

            

             #search

             {

                    color:#343434;

                    border:1px solid gray;

                    width:301px;

                    position:absolute;

                    left:14px;

                    top:91px;

                    background-color:White;

                    display:none;

             }

            

             #searchFooter

             {

                    background-color:#CDCDCD;

                    padding:3px;

             }

            

             .item

             {

                    width:98%;

                    padding:1px;

                    padding-left:5px;

             }

            

             .item:hover

             {

                    background-color:#EDEDED;

                    cursor:pointer;

             }

            

             #searchContent

             {

                    padding-top:5px;

                    padding-bottom:3px;

             }

       </style>

 

       <script src="ajax.js" type="text/javascript"></script>

       <script type="text/javascript">

             var txt, list;

 

             function Init() {

                    txt = document.getElementById("TextBox1");

                    txt.onkeyup = Search;

 

                    list = document.getElementById("search");    

             }

 

             function Search() {

                    //ajax를 통해서 검색어 전송 -> 명단 출력

                    //1. 검색어

                    var search = txt.value;

 

                    if (search == "") {

                           list.style.display = "none";

                    }

 

                    //2. 완성형일때만 반응.. 정규식

                    var regex = /^[-]{1,}$/g;

 

                    if (regex.test(search)) {

                           //3. 완성형으로 입력되었을때만 서버에게 요청

                           //4. ajax 객체

                           myAjax = CreateAjax();

                           //5. 연결 설정

                          myAjax.open("GET", "Ex06Ok.aspx?search=" + encodeURI(search), true);

                           //6. 응답 데이터 이벤트 추가

                           myAjax.onreadystatechange = GetData;

                           //7. 전송

                           myAjax.send("");

                    }

             }

 

             function GetData() {

                    if (myAjax.readyState == 4 && myAjax.status == 200) {

                           var data = myAjax.responseText;

 

                           //뒷처리

                           //가위|가위손|

                           var items = data.split('|');

 

                           document.getElementById("searchContent").innerHTML = "";

 

                           for (i = 0; i < items.length-1; i++) {

                                 //검색어 갯수만큼 -> <div class="item">

                                 var div = document.createElement("div");

                                 div.className = "item";

                                 div.innerText = items[i];

                                 div.onmousedown = function () {

                                        //검색어를 마우스로 선택했을때..

                                        txt.value = event.srcElement.innerText;

                                        list.style.display = "none";

                                 }

 

                                 document.getElementById("searchContent").appendChild(div);

                           }

 

                           list.style.display = "block";

                    }

             }

       </script>

 

</head>

<body onload="Init();">

    <form id="form1" runat="server">

    <div>

   

       <h2>

                    Ex06.aspx</h2>

             <br />

             <asp:TextBox ID="TextBox1" runat="server" autocomplete='off'></asp:TextBox>

             <br />

             <br />

    </div>

 

       <%-- 추천검색어 목록 --%>

       <div id="search">

             <div id="searchContent">

             </div>

             <div id="searchFooter">

                    <div style="float:left;">추천 검색어</div>

                    <div style="float:right;">| 도움말</div>

                    <div style="clear:both;"></div>

             </div>

       </div>

 

    </form>

</body>

</html>

 

 


요청 URL 처리하는 페이지.

Ex06Ok.aspx

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

             //Ex06Ok.aspx?search=가나

             SqlConnection con = new SqlConnection();

             con.ConnectionString = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;

 

             SqlCommand cmd = new SqlCommand();

             cmd.Connection = con;

             cmd.CommandText = string.Format("select item from tblItem where item like '{0}%'", Request.QueryString["search"]);

 

             con.Open();

 

             //검색 결과 -> 가나|가나초콜렛|가나어쩌구

             string result = "";

 

             SqlDataReader reader = cmd.ExecuteReader();

 

             while (reader.Read())

             {

                    result += reader["item"].ToString() + "|";

             }

 

             reader.Close();

             con.Close();

 

             //반환값 생성

             Response.ContentType = "text/plain";//클라이언트에게.. 현재 돌려받은 내용이 텍스트파일입니다.

             Response.Write(result);

             Response.End();

    }

}

 




 

반응형