angularjs中的$ http.get读取txt文件但无法读取json文件

问题描述 投票:1回答:1

我是angularjs的新手,我正在尝试使用json方法从$http.get文件中读取数据,但无法读取它。

当我尝试使用txt读取一个简单的$http.get文件时,它正常读取。

我无法理解我哪里错了...

这是我的代码:

<%@ 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') //when I try to read cities.json error occurs
                  .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 here:</p>
    <pre>{{json}}</pre>
  </body>

</html>

read.txt文件只包含Hello world字符串。

当我尝试读取json文件时then()执行错误功能。

当我徘徊在error变量时,它给了我status作为404statusText作为Not Found

这是json文件cities.json

    {
  "cities": [
    {   
        "city": "Pune", 
        "latitud": "1", 
        "longitud": "2",
        "id": "pun"
    }, 
    {
        "city": "Mumbai", 
        "latitud": "45", 
        "longitud": "23",
        "id": "mum"
    },
    {
        "city": "Delhi", 
        "latitud": "22", 
        "longitud": "676",
        "id": "del"
    },
    {
        "city": "Chennai", 
        "latitud": "45", 
        "longitud": "787",
        "id": "del"
    }
  ]
}

我使用Visual Studio作为IDE

我发现这个例子here,它在那里完美运行。

javascript json angularjs visual-studio
1个回答
0
投票

我已成功运行此代码而没有任何错误,您可以看到工作plunker

如果仍然无法满足您的要求,请使用更新的代码详细说明您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.