使用Angular发送ajax请求时获取错误,以获取.json文件?

时间:2014-08-31 12:04:35

标签: javascript ajax json angularjs http

我有后端创建的.json文件。现在我正在尝试使用Angular.js发出ajax请求,因此我的前端可以使用我的.json文件中的数据。

以下是.json文件的路径:

C:\Users\Mykhaylo Vayvala\Desktop\carBuyer\topCarObj.json

这是我的html文件:

<!DOCTYPE html>
<html ng-app="MyApp">
    <head>
        <title>Top cars</title>
    <head>
    <body ng-controller="PostsCtrl">
      <p>{{posts}}</p>
        <script type="text/javascript" src="angular.min.js"></script>
        <script type="text/javascript" src="carApp.js"></script>
    </body>
</html>

这是我使用Angular.js的JavaScript文件:

var app = angular.module("MyApp", []);

app.controller("PostsCtrl", function($scope, $http) {
  $http.get('topCarObj.json').
    success(function(data, status, headers, config) {
      $scope.posts = data;
    }).
    error(function(data, status, headers, config) {
      alert("AJAX failed")
    });
});

当我在浏览器中运行我的html文件时,我在控制台中收到以下错误:

XMLHttpRequest cannot load file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/topCarObj.json. Cross origin requests are only supported for HTTP. angular.min.js:78
Error: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/topCarObj.json'.
    at Error (native)
    at file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:78:466
    at v (file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:73:464)
    at g (file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:71:294)
    at I (file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:100:144)
    at I (file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:100:144)
    at file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:101:308
    at k.$eval (file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:112:32)
    at k.$digest (file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:109:121)
    at k.$apply (file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:112:362) 

我做错了什么,我该如何解决?

1 个答案:

答案 0 :(得分:2)

将应用程序托管到localhost或尝试其他浏览器。

对于chrome,您可以通过以下方式实现此目的:

chrome.exe --allow-file-access-from-files