簡體   English   中英

angularjs中的$http.get讀取txt文件但無法讀取json文件

[英]$http.get in angularjs reads txt file but could not read json file

我是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變量上時,它給我的status404status statusTextNot 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

我在這里找到了這個例子,它在那里完美運行。

我已成功運行此代碼,沒有任何錯誤,您可以看到工作中的plunker

如果它仍然不能滿足您的要求,請使用更新后的代碼詳細說明您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM