I'm new to angularjs
and I am struggling to retrieve data from a json
file using the $http.get
method. It seems to work fine when I try to read a simple txt
file, but not with the json file.
I can't seem to pinpoint where the issue lies...
Below is the code snippet I am working with:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Plunkr.aspx.cs" Inherits="AngularJS.Plunkr" %>
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<title>content</title>
<script src="jquery-1.8.2.js"></script>
<script src="angular.min.js"></script>
<script type="text/javascript">
angular.module('myApp', [])
.controller('myController', function ($scope, $http) {
$scope.json = 'Cities not yet loaded.';
$http.get('read.txt') // This works fine
.then(function (data) {
debugger;
$scope.json = data.data;
}, function (error) {
debugger;
alert('error');
});
})
;
</script>
</head>
<body data-ng-controller="myController">
<p>JSON content should display below:</p>
<pre>{{json}}</pre>
</body>
</html>
The read.txt
file contains only the text "Hello world".
When attempting to read the json
file, the error
function in the then()
block is triggered.
After inspection, the error
variable displayed a status
of 404
and statusText
as Not Found
.
Here is the contents of the json
file cities.json:
{
"cities": [
{
"city": "Pune",
"latitude": "1",
"longitude": "2",
"id": "pun"
},
{
"city": "Mumbai",
"latitude": "45",
"longitude": "23",
"id": "mum"
},
{
"city": "Delhi",
"latitude": "22",
"longitude": "676",
"id": "del"
},
{
"city": "Chennai",
"latitude": "45",
"longitude": "787",
"id": "chn"
}
]
}
I am using Visual Studio
as my IDE
.
I came across this example here, and it seems to run without issues on that platform.