목차
- 서버에 요청 보내기 기본 구문
- GET 방식 vs. POST 방식
- AJAX GET 방식
- AJAX POST 방식
- setRequestHeader() 메서드
- onreadystatechange 속성
- [참고] 동기식 요청 방식
- XMLHttpRequest 객체는 서버와 데이터를 교환하는 데 사용됨.
- 서버에 요청 보내려면 XMLHttpRequest객체의 open() 및 send() 메서드 사용
서버에 요청 보내기 기본 구문
xhttp = new XMLHttpRequest();
xhttp.open("GET", "a.php", true);
xhttp.send();
[매개변수] - open() 경우
open (method, url, async, user, psw)
요청 내용 구체화.
method
필수. 요청 방식. GET 또는 POST
url
필수. 불러올 파일 주소.
- 파일은 모든 종류 가능 (예: txt, xml, php, asp 등)
async
필수. true (비동기)・false (동기)
- 서버 요청은 true (비동기)로 보내야 함.
- true (비동기)로 보내면 JS는 서버 응답을 기다릴 필요 없으며, 서버 응답 기다리는 동안 다른 작업 수행하다가 응답 준비 되면 응답처리 가능.
user
선택. 사용자 이름
psw
선택. 암호
[매개변수] - send() 경우
send()
서버에 요청 보내기. GET 방식 요청일 때 사용.
send (string)
서버에 요청 보냄. POST 방식 요청일 때 사용.
GET 방식 vs. POST 방식
GET 방식 요청은 POST 방식보다 간단하고 빠르며, 대부분 경우 사용 가능. 그러나, 다음 경우엔 항상 POST 방식 요청 사용할 것 !!
- 캐시 안 된 파일 호출 경우. (예: 파일 또는 DB 업데이트된 경우).
- 많은 데이터를 서버에 전송 경우. (※ POST 방식은 크기 제한 없음).
- 보안이 필요한 내용 전송. (※ POST는 GET보다 강력하고 안전)
AJAX GET 방식
예제1 - 캐시 제어
b.php (캐시 불러올 가능성 존재)
<button type="button" onclick="hz()">클릭</button>
<p id="demo"></p>
<script>
function hz() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "a.php", true);
xhttp.send();
}
</script>
b.php (※ 캐시된 결과를 가져오는 걸 피하기 위해 URL 주소에 고유 아이디 추가)
<button type="button" onclick="loadDoc()">클릭</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "a.php?t=" + Math.random(), true);
xhttp.send();
}
</script>
a.php (불러올 파일)
<h1>홈짱닷컴 소개 Homzzang.com</h1>
<p>HTML - 기본틀</p>
<p>CSS - 디자인</p>
<p>JS - 동작기능</p>
<p>요청 방식 : <?php echo $_SERVER['REQUEST_METHOD']?> 방식</p>
<p>요청 시간 : <?php echo date("Y:m:d h:i:s", $_SERVER['REQUEST_TIME'])?></p>
예제2 - 서버로 데이터 보내서 데이터 반영 결과 받아오기
b.php
<button type="button" onclick="hz()">클릭</button>
<p id="demo"></p>
<script>
function hz() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "a.php?x1=SQL&x2=DB&y1=PHP&y2=서버언어", true);
xhttp.send();
}
</script>
a.php (불러올 파일)
<?php
$x1 = $_GET['x1'];
$x2 = $_GET['x2'];
$y1 = $_GET['y1'];
$y2 = $_GET['y2'];
?>
<h1>홈짱닷컴 소개 Homzzang.com</h1>
<p>HTML - 기본틀</p>
<p>CSS - 디자인</p>
<p>JS - 동작기능</p>
<p><?php echo $x1?> - <?php echo $x2?></p>
<p><?php echo $y1?> - <?php echo $y2?></p>
<p>요청 방식 : <?php echo $_SERVER['REQUEST_METHOD']?> 방식</p>
<p>요청 시간 : <?php echo date("Y:m:d h:i:s", $_SERVER['REQUEST_TIME'])?></p>
AJAX POST 방식
예제1
b.php
<button type="button" onclick="hz()">클릭</button>
<p id="demo"></p>
<script>
function hz() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "a.php", true);
xhttp.send();
}
</script>
a.php (불러올 파일)
<h1>홈짱닷컴 소개 Homzzang.com</h1>
<p>HTML - 기본틀</p>
<p>CSS - 디자인</p>
<p>JS - 동작기능</p>
<p>요청 방식 : <?php echo $_SERVER['REQUEST_METHOD']?> 방식</p>
<p>요청 시간 : <?php echo date("Y:m:d h:i:s", $_SERVER['REQUEST_TIME'])?></p>
예제2 - 서버로 데이터 보내서 데이터 반영 결과 받아오기
b.php
<button type="button" onclick="hz()">클릭</button>
<p id="demo"></p>
<script>
function hz() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "a.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("x1=PHP&x2=서버언어&y1=SQL&y2=DB");
}
</script>
a.php (불러올 파일)
<?php
$x1 = $_POST['x1'];
$x2 = $_POST['x2'];
$y1 = $_POST['y1'];
$y2 = $_POST['y2'];
?>
<h1>홈짱닷컴 소개 Homzzang.com</h1>
<p>HTML - 기본틀</p>
<p>CSS - 디자인</p>
<p>JS - 동작기능</p>
<p><?php echo $x1?> - <?php echo $x2?></p>
<p><?php echo $y1?> - <?php echo $y2?></p>
<p>요청 방식 : <?php echo $_SERVER['REQUEST_METHOD']?> 방식</p>
<p>요청 시간 : <?php echo date("Y:m:d h:i:s", $_SERVER['REQUEST_TIME'])?></p>
setRequestHeader() 메서드
요청에 HTTP 헤더를 추가.
[구문]
setRequestHeader (header, value)
[매개변수]
- header - 헤더 이름
- value - 헤더 값
onreadystatechange 속성
1.
XMLHttpRequest 객체를 사용하면, 요청이 응답을 받을 때 실행할 함수 정의 가능. (이 함수는 XMLHttpResponse 객체의 onreadystatechange 속성 안에 정의 함.)
2.
비동기식일 때만 필요. (※ 동기식일 땐 코드가 서버 완료 기다려야 하므로 불필요)
(예제)
b.php
<button type="button" onclick="hz()">클릭</button>
</div>
<script>
function hz() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "a.php", true);
xhttp.send();
}
</script>
a.php (불러올 파일)
<h1>홈짱닷컴 소개 Homzzang.com</h1>
<p>HTML - 기본틀</p>
<p>CSS - 디자인</p>
<p>JS - 동작기능</p>
<p>요청 방식 : <?php echo $_SERVER['REQUEST_METHOD']?> 방식</p>
<p>요청 시간 : <?php echo date("Y:m:d h:i:s", $_SERVER['REQUEST_TIME'])?></p>
[참고] 동기식 요청 방식
1.
동기식 요청하려면 open() 메서드의 세번째 매개변수를 false로 설정.
xhttp.open("GET", "a.php", false);
2.
- 빠른 테스트를 위해서 아주 가끔 이용. (옛날 JS 코드에서도 이용된 적 있음)
- 코드가 서버 완료 기다려야 하므로, onreadystatechange 함수는 불필요.
- 동기식은 최근 웹표준에서 제거되는 추세이니, 되도록이면 사용하지 말 것 !! (왜냐면, 서버가 느린 경우에 응용 프로그램이 맛이 가는 문제 발생하기 때문.)
(예제)
b.php
<button type="button" onclick="hz()">클릭</button>
<p id="demo">코딩 배우기 좋은 사이트는 어디?</p>
<script>
function hz() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "a.php", false);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;
}
</script>
a.php (불러올 파일)
<h1>홈짱닷컴 소개 Homzzang.com</h1>
<p>HTML - 기본틀</p>
<p>CSS - 디자인</p>
<p>JS - 동작기능</p>
<p>요청 방식 : <?php echo $_SERVER['REQUEST_METHOD']?> 방식</p>
<p>요청 시간 : <?php echo date("Y:m:d h:i:s", $_SERVER['REQUEST_TIME'])?></p>