Created
June 6, 2015 04:16
-
-
Save sundaycrafts/0ef0b73c9c02c7816e1c to your computer and use it in GitHub Desktop.
js: AJAX load JSON very simple example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "sundaycrafts", | |
"age": 18, | |
"gender": "male", | |
"msg": "<h1>Hello World!</h1>" | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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