Ajax
Html 에서 $.ajax로 .json 호출
웨이칭
2020. 7. 24. 12:29
index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<p id="demo"></p>
<br>
<button type="button">click</button>
<script type="text/javascript">
//html로 ajax사용
$(function () {
$("button").click(function() {
$.ajax({
//String을 jon으로 변환(함수) : JSON.parse
//json을 String으로 변환(함수) : JSON.stringify
url:"data.json",
type:"get",
datatype:"json",
success:function(json){
//alert("success");
//alert(json);//[object Object],[object Object],[object Object]
//let str = JSON.stringify(json);//json을 문자열로 변환
//alert(str);
/* 값 : {"name":"성춘향","age":16,"address":"화성시","phone":"890"}] */
//alert(json[0].name+ " " + json[0].age);//홍길동 24
/* for (var i = 0; i < json.length; i++) {
$("#demo").append(json[i].name+" ");
$("#demo").append(json[i].age+" ");
$("#demo").append(json[i].address+" ");
$("#demo").append(json[i].phon+"<br>");
} */
$.each(json, function(index, item) { //each문으로 table id값으로 추가만 해주면 됨
$("#demo").append(index+" ");
$("#demo").append(item.name+" ");
$("#demo").append(item.age+" ");
$("#demo").append(item.address+" ");
$("#demo").append(item.phone+"<br>");
//값 : 0 홍길동 24 서울시 123
})
},
error:function(){
alert("error");
}
});
});
});
</script>
</body>
</html>
data.json
[{
"name" : "홍길동",
"age" : 24,
"address" : "서울시",
"phone" : "123"
},
{
"name" : "일지매",
"age" : 21,
"address" : "수원시",
"phone" : "435"
},
{
"name" : "성춘향",
"age" : 16,
"address" : "화성시",
"phone" : "890"
}]