Reputation: 399
I am new to Javascript and jQuery and I am trying to retrieve data from a JSON file using getJSON method in jQuery. However I am unable to do so. Here is the code:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<title>JSON Test</title>
</head>
<body>
<script type="text/javascript">
console.log("Hi");
$.getJSON('red.json', function(data){
console.log("This is the Data" + data["Live Births"])});
var response = $.getJSON( "red.json", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
</script>
</body>
</html>
JSON:
{"Live Births" : [
[11.925, 76.9502],
[11.896, 76.9492],
[11.990, 76.9602],
[11.911, 76.9402],
[11.978, 76.8902]
],
"Still Births" : [
[11.986, 76.9402],
[11.896, 76.9602],
[11.966, 76.8992],
[11.916, 76.8902],
[11.946, 76.9002]
]}
Awaiting your responses.
Regards,
Jones
A fiddle Demo to the problem is added
Upvotes: 0
Views: 4690
Reputation: 5712
I have implement your code at my local server and it works fine. Here is what I used:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<title>JSON Test</title>
</head>
<body>
<script type="text/javascript">
alert("Hi");
$.getJSON('red.json', function(data){
alert("This is the Data" + data["Live Births"])});
</script>
</body>
</html>
The only difference is the link to the jQuery library ( maybe is this the problem at your side? ).
JSON (red.json):
{
"Live Births" : [
[11.925, 76.9502],
[11.896, 76.9492],
[11.990, 76.9602],
[11.911, 76.9402],
[11.978, 76.8902]
],
"Still Births" : [
[11.986, 76.9402],
[11.896, 76.9602],
[11.966, 76.8992],
[11.916, 76.8902],
[11.946, 76.9002]
]
}
Located in the same directory as your html file.
Edit:
This is what I have done:
Create a new file ( index.html ) and paste your html code in it. Then create a new file red.json with your json data. Put those two files in one directory and open index.html.
Upvotes: 1
Reputation: 147
Please try with this
<script type="text/javascript">
console.log("Hi")
$(function(){
$.getJSON('red.json', function(data){
console.log("This is the Data" + data)});
});
// please add these handler
var response = $.getJSON( "red.json", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
</script>
Upvotes: 0