【问题标题】:$http.get in angularjs reads txt file but could not read json fileangularjs 中的 $http.get 读取 txt 文件但无法读取 json 文件
【发布时间】:2015-09-08 06:33:15
【问题描述】:

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

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

我不明白我哪里错了......

这是我的代码:

<%@ 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文件city.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,它在那里完美运行。

【问题讨论】:

  • 我无法理解 JSON 文件的错误是什么
  • 是的,听起来你的端点有问题,而不是你的 json 文件。

标签: javascript json angularjs visual-studio


【解决方案1】:

我已经成功运行了这段代码,没有任何错误,你可以看到工作plunker

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

【讨论】:

  • 当我们将文本文件作为参数传递给$http.get()时它会运行,但是当我们传递json文件时它会失败
  • 它与 readfile.json plnkr.co/edit/O9FNpQmBBS4T3cMrvBUF?p=preview一起运行也很好
  • 你能分享你的 json 文件,或者控制台你的承诺结果数据,你到那里的错误是什么
  • 嘿,我发现了错误。它不在我的代码中。我不得不重新配置我的 IIS 来解决这个错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
相关资源
最近更新 更多