js
JS - Ajax POST 예제
전송 버튼을 클릭하면 test.php 에 POST 로 name 과 age 값을 함께 전송합니다. 이렇게 전송된 값은 id 속성 "test" 에 결과 값이 출력되는 예제입니다.
test.php 파일에는 아래 내용으로 작성되었을 때의 결과입니다.
test.php 파일에는 아래 내용으로 작성되었을 때의 결과입니다.
// test.php 내용
<?php print_r($_POST); ?>
<script>
function getXMLHttps() {
if (typeof XMLHttpRequest != 'undefined') {
return new XMLHttpRequest();
} else {
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Ajax를 지원하는 브라우저가 아닙니다.");
return;
}
}
}
}
function dynamic(){
var req = getXMLHttps();
req.onreadystatechange = function(){
if (this.readyState === 4 && this.status === 200) {
parseText(this.responseText);
}
}
// 사용자 정의 함수
parseText = function(data) {
document.getElementById("test").innerHTML = data;
}
// 요청을 POST, 비동기로 합니다.
// 요청을 test.php 로 보냅니다.
req.open("POST", "test.php", true);
// 헤더를 설정합니다.
req.setRequestHeader(
'Content-Type', 'application/x-www-form-urlencoded'
);
req.setRequestHeader(
'Cache-Control', 'no-cache'
);
// POST 라면 파라미터를 설정합니다.
req.send(
"name=" + encodeURIComponent("habony")
+ "&age=" + encodeURIComponent(20)
);
}
</script>
<div id="test"></div>
<button onclick="dynamic()">전송</button>
<!--
결과:
Array (
[name] => habony
[age] => 20
)
-->
0 댓글