Skip to content

Instantly share code, notes, and snippets.

@ybouhjira
Created January 31, 2014 20:57
Show Gist options
  • Save ybouhjira/8742982 to your computer and use it in GitHub Desktop.
Save ybouhjira/8742982 to your computer and use it in GitHub Desktop.
XMLHttpRequest example
<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