Created
February 27, 2016 17:34
-
-
Save deepakkj/90fe651709cc578ec4e4 to your computer and use it in GitHub Desktop.
Fetching JSON data using 'GET' method
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> | |
<head> | |
<script src="https://code.jquery.com/jquery-1.11.3.js"></script> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>Deepak Kumar Jain</title> | |
</head> | |
<body> | |
<h1>Fetching JSON data using 'GET' method</h1> | |
<h4>-Using Jquery and REST API</h4> | |
<small>Thanks to http://rest.learncode.academy/ for providing the RESTful API </small> | |
<h2>Friends Detail</h2> | |
<ul id="friends_details"></ul> | |
<script> | |
//storing the id name in a variable to enable caching it, making the program run faster, i.e. there is no need for JS/Jquery to search the element in the DOM everytime it is needed. | |
var $friends_details = $("#friends_details"); | |
//function to append and display the friends data. | |
function display_name(data){ | |
for (var i in data){ | |
//checking if key matches the its value. This is to ensure that no extra data/property is added to json data while performing this function | |
if(data.hasOwnProperty(i)){ | |
$friends_details.append("<li><ul>" +"<li> Name: "+data[i].name+ "</li>" +"<li> Drink: "+data[i].drink+ "</li>" +"<li> Id: "+data[i].id+ "</li>" + "</ul></li>"); | |
} | |
} | |
} | |
//using AJAX to reterive the JSON data from the given URL and call respective functions on success/error. | |
//URL used is only for learning/educational purposes. Cannot be used for production. | |
$.ajax({ | |
type: "GET", | |
url : "http://rest.learncode.academy/api/learncode/friends" , | |
success : function(data){ | |
display_name(data); | |
}, | |
error: function(){ | |
console.log("Error receving data"); | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check here at : http://jsbin.com/xuciju/