Native Javascript Ready Function and JSON with AJAX GET Request
- Categories:
- javascript
I use You Might Not Need jQuery as reference when building something with Native Javascript.
In this post I write about example usage for ready function and JSON with AJAX GET request. For POST request, please see my previous Native Javascript AJAX POST Request with Data or Parameters.
The code below is ready function based on jQuery and Native Javascript.
// jQuery
$(document).ready(function(){
});
// Native JS, IE 9+
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
And the code below is JSON GET request based on jQuery and Native Javascript.
// jQuery
$.getJSON('/my/url', function(data) {
});
// Native JS, IE 10+
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var data = JSON.parse(this.response);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
Example Usage
Suppose there’s HTML like this:
<div id="my-selector">
</div>
And JSON response like this:
{
"example": {
"foo": "bar"
}
}
Here is example code how to insert HTML element from JSON response with Native Javascript.
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
ready(function() {
var request = new XMLHttpRequest();
request.open('GET', 'https://example.com', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
var data = JSON.parse(this.response);
var element = document.getElementById('my-selector');
if (data['example'] == null) {
element.innerHTML = '<p>Empty resultt</p>';
} else {
element.innerHTML = '<p>'+ data['example']['foo']+'</p>';
}
} else {
console.log('server error');
}
};
request.onerror = function() {
console.log('request error');
};
request.send();
});
- Tags:
- #javascript
- #ajax
- #json
Recent Posts
AWS Secrets Manager
Explanation about AWS Secrets Manager with example code.
Envelope Encryption
Envelope encryption is the practice of encrypting plaintext data with a data key, and then encrypting the data key under another key.
Tutorial - "su username vs su - username" - A Security Perspective
The main difference between `su username` and `su - username` lies in the environment variables that are loaded when switching to the specified user.
Subdomain Hijacking
My dormant subdomain was recently hijacked, redirecting it to a online gamble registration page.
C# DbContext ServiceLifeTime
my note about C Sharp ServiceLifeTime