Use Jquery to retrieve JSON file data
Introduction:
In this article,i am going to explain about how to retrieve json file data・s using
jquery.
Main:
The JSON file is a file that contains information regarding .name・ and .value・ pairs.
for ex,
sample1.json,
[
{"optiontext" : "One", "optionvalue" : "One"},
{"optiontext" : "Two", "optionvalue" : "Two"},
{"optiontext" : "Three", "optionvalue" : "Three"}
]
We can see information is stored here in the form of two attributes optiontext and optionvalue.
The jQuery code to import the information from JSON file, and display it in the form of list
items in the current web page, is as follows:
$(document).ready(function() {
$('#submit').click(function () {
$.ajax({
type:"GET",
url:"sample1.json",
dataType:"json",
success: function (data) {
var SampleFileMessage="
";
$.each(data, function(i,n){
SampleFileMessage+="- "+n["optiontext"]+"
";
});
SampleFileMessage+="
";
$('#message').append(SampleFileMessage);
}
});
return false;
});
});
In the above jQuery code we attach a click event to the submit button that is assigned the id submit
and we invoke the request through the ajax() method, where we specify that the method of request that
we are going to use is GET and the url of the JSON file on the server is Sampl1.json.
We also assert that the value of the dataType key is set to json to signal that the url contains the data in
JSON encoded form.
The information loaded from the JSON file (which is assumed to be present on the server) is returned to the JavaScript file,
in the form of response generated from the server, and then received in the parameter data of the callback function.
Here of course, data is an array of objects where each element has the attributes optiontext and optionvalue,
which match the attributes in JSON file we・re working with.We next initialize a variable SampleFileMessage and assign
it a tag ul because we want to send the response to the web page in the form of an unordered list.
The information received in data contains two attributes: optiontext and optionvalue, and we want to return only
the contents of the optiontext attribute to the web page,
in the form of a list. We therefore make use of the each() method to parse each object stored in data.
In the callback function of each() method,we use two parameters: i and n where i refers to the index location of the
object in data and n refers to object containing information (in terms of attributes optiontext and optionvalue).
We extract the information in attribute optiontext from the n object one by one,and nest it in between the li tags
(to make them appear as list items) and concatenate them in the SampleFileMessage variable.
Conclusion:
Hope this helps,
Happy Coding.