ASP.NET에서 XMLHTTP를 사용한 아작스(AJAX) 예제입니다.

저는 평소에 에이잭스라고 발음하는데 아작스라고 하시는 분들도 계시더라구요.


사용하는 파일은 총 2개입니다.

clientToCall.html(폼)

process.aspx.cs(Db에서 데이터 블러오는 작업)




clientToCall.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>XMLHTTP TEST</title>

    <Script language="JavaScript">

        function GetInfo() {

            var article_id = document.all.article_id.value;

            if (article_id == "") {

                alert('article_id를 입력 후 버튼을 클릭하세요.\n\n322');

                return;

            }

            var pageUrl = "process.aspx?article_id=" + article_id;


            //var xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");

            var xmlRequest = null;

            if (window.ActiveXObject) {

                xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");

            } else if (window.XMLHttpRequest) {

                xmlRequest = new XMLHttpRequest();

            }

            xmlRequest.open("POST", pageUrl, true);

            xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            xmlRequest.onreadystatechange = function () { CallBack(xmlRequest) };

            xmlRequest.send(null);


            return xmlRequest;

        }


        function CallBack(xmlRequest) {

            if (xmlRequest == null || xmlRequest.readyState != 4) return;

            if (xmlRequest.responseText.length == 0) return;


            var vals = xmlRequest.responseText.split("|");


            document.all.title.innerHTML = vals[0];

            document.all.posting_date.innerHTML = vals[1];

            document.all.read_count.innerHTML = vals[2];

            document.all.content.innerHTML = vals[3];

        }


    </Script>

    </head>

    <body>

    <p>

        <table cellpadding="3">

            <tr>

                <td align="center" colspan="2">XMLHTTP 테스트</td>

            </tr>

            <tr>

                <td>글번호</td>

                <td width="500"><input id="article_id" NAME="article_id" value="322" />&nbsp;&nbsp;<input type="button" value="getXMLHTTP" name="getXMLHTTP" id="getXMLHTTP" onclick="GetInfo();" /></td>

            </tr>

            <tr>

                <td height="10">&nbsp;</td>

            </tr>

            <tr>

                <td width="80">제목</td>

                <td ><div id="title"></div></td>

            </tr>

            <tr>

                <td>작성일</td>

                <td><div id="posting_date" name="posting_date"></div></td>

            </tr>

            <tr>

                <td>조회수</td>

                <td><div id="read_count" name="read_count"></div></td>

            </tr>

            <tr>

                <td>내용</td>

                <td><div id="content" name="content"></div></td>

            </tr>

        </table>

    </p>


    </body>

</html>


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

HTML폼 화면


getXMLHTTP 버튼을 클릭 후 실행 결과 화면


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



process.aspx.cs(DB 연결 후 데이터 불러오기)
 - 아래 소스는 오라클(ORACLE) 연결 방법입니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using System.Data;

namespace WebApplication1.AjaxTest
{
    public partial class process : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
//DB 접속 정보 수정하시면 됩니다.
            string CONNECTSTR = "User Id=아이디;Password=비밀번호;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=호스트)(PORT=포트번호)))(CONNECT_DATA=(SERVICE_NAME=서비스명)));";
            
            OracleConnection OraConn = new OracleConnection(CONNECTSTR);
            OracleCommand CmdOra = new OracleCommand();
            OraConn.Open();
            CmdOra.Connection = OraConn;

            string sqlString = "SELECT TITLE, TO_DATE(TO_CHAR(POSTING_DATE,'YYYY-MM-DD')) POSTING_DATE, READ_COUNT, CONTENT FROM FREE_BOARD WHERE ARTICLE_ID = :ARTICLE_ID ";
            CmdOra.CommandText = sqlString;

            //OracleDataAdapter OrclAd = new OracleDataAdapter(sqlString, OraConn);
            CmdOra.Parameters.Add(new OracleParameter("ARTICLE_ID", OracleType.Number));
            string article_id = Request.QueryString["article_id"].ToString();
            CmdOra.Parameters["ARTICLE_ID"].Value = article_id;

            OracleDataReader reader = CmdOra.ExecuteReader(CommandBehavior.CloseConnection);

            string xmlData = "";
            if (reader.Read())
            {
                xmlData = reader["TITLE"].ToString().Trim() + "|";
                xmlData += reader["POSTING_DATE"].ToString().Trim() + "|";
                xmlData += reader["READ_COUNT"].ToString().Trim() + "|";
                xmlData += reader["CONTENT"].ToString().Trim();
            }
            else
            {
                xmlData = "|||";
            }
            OraConn.Close();

            Response.Write(xmlData);
            Response.End();
        }
    }
}

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


process.aspx?article_id=322 실행 화면(| 문자로 구분)


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



process.aspx(수정사항 없음-기본상태이므로 건드실 필요가 없습니다.)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="process.aspx.cs" Inherits="WebApplication1.AjaxTest.process" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

Posted by 준콩ol 준콩ol

댓글을 달아 주세요