ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

JS

ajax ๋‘๋ฒˆ์งธ

๐Ÿ”ฅ fire 2010. 7. 13. 20:23

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>์ค‘๋ณต์•„์ด๋”” ์ฒดํฌ</title>
<script type="text/javascript">
 window.onload = function() {
  //id๋ผ๋Š” ์š”์†Œ๋ฅผ ์ฐพ๋Š”๋‹ค.
  var id = document.getElementById("id");

  //์ด๋ฒคํŠธ๋“ฑ๋ก
  id.onkeyup = function() {
   //id๊ฐ’์„ ์ฝ์–ด์„œ ์„œ๋ฒ„๋กœ ์ „์†กํ•˜๋„๋ก ํ•˜๋Š” ํ•จ์ˆ˜ํ˜ธ์ถœ
   sendRequest(id.value);
  }
 }

 var req = null;

 function sendRequest(data) {
  //1. xhr ๊ฐ์ฒดํ•„์š”
  req = getXMLHttpRequest();

  if(req == null) {
   alert("XMLHttpRequest ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.");
   return;
  }

  //2. xhr ๊ฐ์ฒด์˜ ํ”„๋กœํผํ‹ฐ ์„ค์ • ๋ฐ ๋ฉ”์†Œ๋“œ ํ˜ธ์ถœ
  req.open("POST", "ajax02Process.jsp", true);
  req.onreadystatechange = callback;
  req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

  //3. ํŒŒ๋ผ๋ฏธํ„ฐ ๋ฐ›๊ธฐ
  var param = "id=" + encodeURIComponent(data);

  //4. ์ „์†ก
  req.send(param); //POST๋ฐฉ์‹์—์„œ๋Š” ๊ฐ’์„ ์ง€์ •ํ•œ๋‹ค.  
 }

 function callback() {
  var check = document.getElementById("check");
 
  if(req.readyState == 4) {
   if(req.status == 200) {
    //์„œ๋ฒ„์—์„œ ๋ณด๋‚ด์˜จ ์ •๋ณด๋ฅผ ์ฝ์–ด๋ณด์ž
    var receiveData = req.responseText;
    if(receiveData == "available") {
     //์‚ฌ์šฉ๊ฐ€๋Šฅํ•œ ์•„์ด๋””
     check.style.color = "green";
     check.innerHTML = "์‚ฌ์šฉ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. ";
    } else {
     //์ด๋ฏธ ์‚ฌ์šฉ์ค‘์ธ ์•„์ด๋””
     check.style.color = "orange";
     check.innerHTML = "์ด๋ฏธ ์‚ฌ์šฉ์ค‘์ž…๋‹ˆ๋‹ค.";
    }
   } else {
    check.style.color = "red";
    check.innerHTML = "์˜ค๋ฅ˜ : " + req.statusText;
   }
  }
 }

 function getXMLHttpRequest() {
  //๊ฐ์ฒดํƒ์ง€๊ธฐ๋ฒ•์œผ๋กœ
  if(window.XMLHttpRequest) {
   return new XMLHttpRequest();  
  } else if (window.ActiveXObject) {
   try {
    return new ActiveXObject("Msxml2.XMLHTTP");
   } catch (e) {
    try {
     return new ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) { return null; }
   }
  } else {
   return null;
  }
 }
</script>
</head>
<body>
 
 ID : <input type="text" id="id" />
 <span id="check"></span>
 
</body>
</html>

'JS' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

ajax ๋‘๋ฒˆ์งธ  (0) 2010.07.13
ajax ๋‘๋ฒˆ์งธ  (0) 2010.07.13
Ajax ์‹œ์ž‘_์ฒ˜๋ฆฌํŽ˜์ด์ง€  (0) 2010.07.12
Ajax ์‹œ์ž‘  (0) 2010.07.12
DOM ๊ฐ์ฒด 02  (0) 2010.07.09
๋Œ“๊ธ€