Javascript example to Fetch JSON using http GET

In this post, we describes the simple example of javascript code which is used to get the JSON from remote server ( although we have shown as localhost, you can change it to remote server url ) and print it to browser console.

First, lets create the demo json in our server as,

$ vim demo.json 
[bash] [ { “name” : “abcdefg”, “class” : “first” }, { “name” : “xyz”, “class”: “fifth” } ] [/bash]

Now, we will write the html code which has the javascript code to fetch this json,

$ vim fetchjson.html 

Fetch JSON using JavaScript


As you can see above, the actual java code which fetch the json is,

[bash] [/bash]

the code is very simple, we have defined “weburl” where we are fetching the JSON. method: “GET” declares it has http GET request. dataType is “json” to declare we are fetching JSON, “success:function(data)” is called after successful download of the JSON from the server. If our json is not present at the url, http GET will return “404 (Not Found)”

Now, lets copy this demo.json and fetchjson.html to our local machines apache webserver /var/www/html and open fetchjson.html in browser as, http://localhost/fetchjson.html

now, when we open the browser console, we can see the JSON as,

This is similar to jquery API

Leave a Comment