Created
January 31, 2014 20:57
-
-
Save ybouhjira/8742982 to your computer and use it in GitHub Desktop.
XMLHttpRequest example
This file contains 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
<html> | |
<head> | |
<title>Learning ajax</title> | |
<meta charset="utf-8" /> | |
</head> | |
<body> | |
<script> | |
(function main () { | |
var httpRequest = new XMLHttpRequest(); | |
httpRequest.onreadystatechange = function () { | |
print_response(httpRequest); | |
}; | |
httpRequest.open('GET', 'http://localhost/response.json'); | |
httpRequest.send(null); | |
})(); | |
function json_to_html_table(jsonObject) { | |
document.write('<table>'); | |
document.write('<tr><td>Key</td><td>Value</td></tr>'); | |
for (key in jsonObject) | |
document.write('<tr><td>' + key + '</td><td>' + jsonObject[key]+ '</td></tr>'); | |
document.write('</table>'); | |
} | |
function print_response(httpRequest) { | |
if(httpRequest.readyState === 4) | |
if(httpRequest.status === 200) | |
json_to_html_table(JSON.parse(httpRequest.responseText)); | |
else | |
alert('failure (status = ', httpRequest.status, ')'); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment