test.json
{
"name": "Lee", "gender": "male", "age": "20"
}
ajax-js.html
ajax-js.html
function getJson(type) {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/data/test.json');
xhr.send();
xhr.onreadystatechange = function (e) {
if(xhr.readyState !== XMLHttpRequest.DONE) return;
if(xhr.status === 200){
const data = JSON.parse(xhr.responseText);
const area= document.querySelector('#area');
area.textContent = type + ': ' + data[type];
// if(type==='name'){
// area.textContent = data.name;
// } else if(type==='gender'){
// area.textContent = data.gender;
// }else if(type==='age'){
// area.textContent = data.age;
// }
console.log(data.name);
} else{
console.log('error!');
}
}
}
window.onload = function () {
const nameBtn = document.querySelector('#nameBtn');
const genderBtn = document.querySelector('#genderBtn');
const ageBtn = document.querySelector('#ageBtn');
nameBtn.onclick = function () {
getJson('name');
}
genderBtn.onclick = function () {
getJson('gender');
}
ageBtn.onclick = function () {
getJson('age');
}
}
name
gender
age
ajax-jquery.html
ajax-jquery.html
const getJson = function (type) {
const param = {id:'hong',pw:'1111'};
$.ajax({
contentType: "application/json",
type:'GET',
url:'/data/test.json',
dataType:'json',
//data:JSON.stringify(param),
success: function (data) {
console.log(data);
let v = '<strong>' + type + ':' + data[type] + '</strong>';
//$('#area').text(v);
$('#area').html(v);
},
error: function (request, status, error) {
console.log(request, status,error);
}
});
}
$(function () {
const nameBtn = document.querySelector('#nameBtn');
const genderBtn = document.querySelector('#genderBtn');
const ageBtn = document.querySelector('#ageBtn');
nameBtn.onclick = function () {
getJson('name');
}
genderBtn.onclick = function () {
getJson('gender');
}
ageBtn.onclick = function () {
getJson('age');
}
});
name
gender
age