js
JS - Ajax JSON 예제
JSON데이터를 ajax 로 받아오는 예제입니다. GET 으로 jsondata.php 에 요청하고, 그 결과 값을 보기좋게 HTML로 출력합니다.
jsondata.php 에는 아래 json 으로 구성되어 있을 때의 결과입니다.
jsondata.php 에는 아래 json 으로 구성되어 있을 때의 결과입니다.
<?php header("Content-Type: application/json"); ?>
{ "name":"하보니", "age":20, "job":"백수" }
<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) {
parseJSON(this.responseText);
}
}
// 사용자 정의 함수
parseJSON = function(data) {
// JSON 데이터를 javascript 객체로 변환합니다.
var a = JSON.parse(data);
document.getElementById("test").innerHTML =
"name: " + a.name + "<br/>age: " + a.age + "<br/>job: " + a.job;
}
req.open("GET", "jsondata.php", true);
req.send();
}
</script>
<div id="test"></div>
<button onclick="dynamic()">전송</button>
<!--
결과:
name: 하보니
age: 20
job: 백수
-->
0 댓글