Javascript Angularjs 访问本地 json 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26649460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:11:20  来源:igfitidea点击:

Angularjs access local json files

javascriptjsonangularjs

提问by Jibo

I am new to angularjs and I've been searching on the web the whole day just to find a solution in getting data from a local json file without having to use a localhost for my webapp. Unfortunately, I haven't found any. I tried using $http.get but I get Cross Origin * error.

我是 angularjs 的新手,我一整天都在网上搜索,只是为了找到从本地 json 文件获取数据的解决方案,而不必为我的 web 应用程序使用本地主机。不幸的是,我还没有找到任何。我尝试使用 $http.get 但我收到 Cross Origin * 错误。

Is there no other way that I could get the data from my local json file without having to locally host my webapp?

有没有其他方法可以从我的本地 json 文件中获取数据而不必在本地托管我的 web 应用程序?

Does angularjs have any other function to get data from local json files without having to use its $http.get?

angularjs 是否有任何其他功能可以从本地 json 文件中获取数据而无需使用其 $http.get?

采纳答案by Grissom

You need to deploy your application to some http server, the easiest way to this is using node, here is the exmaple https://www.npmjs.org/package/http-server, or you can change you browser security settings.

您需要将应用程序部署到某个 http 服务器,最简单的方法是使用节点,这里是示例https://www.npmjs.org/package/http-server,或者您可以更改浏览器安全设置。

回答by Kutyel

You can refer to json file calling them with a GETmethod, like so:

您可以参考 json 文件使用GET方法调用它们,如下所示:

$http.get('phones/phones.json').success(function(data) {
   $scope.phones = data;
});

Check the official AngularJS tutorialto see what you are doing wrong.

查看官方的 AngularJS 教程,看看你做错了什么。

Update:

更新:

For angular 1.6+successmethod is not valid anymore instead use then:

对于 angular 1.6+success方法不再有效,而是使用then

$http.get('phones/phones.json').then(function(data) {
   $scope.phones = data;
});

Refer to source here.

请参阅此处的来源。