Skip to content

Instantly share code, notes, and snippets.

@sundaycrafts
Created June 6, 2015 04:16
Show Gist options
  • Save sundaycrafts/0ef0b73c9c02c7816e1c to your computer and use it in GitHub Desktop.
Save sundaycrafts/0ef0b73c9c02c7816e1c to your computer and use it in GitHub Desktop.
js: AJAX load JSON very simple example
{
"name": "sundaycrafts",
"age": 18,
"gender": "male",
"msg": "<h1>Hello World!</h1>"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
window.onload = function() {
var xhr = new XMLHttpRequest();
var data;
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
data = JSON.parse(xhr.responseText);
}
}
xhr.open('GET', 'data.json');
xhr.send();
var btn = document.querySelector('#btn');
var txt = document.querySelector('#txt');
btn.addEventListener('click', function(){
txt.innerHTML = data.msg;
});
}
</script>
</head>
<body>
<div id="cont">
<button id="btn">push</button>
<div id="txt"></div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment