【发布时间】:2016-04-09 10:16:08
【问题描述】:
我和这个话题的人有同样的问题: $http.get doesn't load JSON
无论哪种方式都找不到解决方案。 我使用 MAMP 运行网站,所以我猜这不是问题?
代码如下:
index.html
<!DOCTYPE HTML>
<html ng-app="myQuiz">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test Your Knowledge: Saturn</title>
<link rel="stylesheet" type="text/css" href="css/quiz.css">
<script type="text/javascript" ng-src="js/angular.min.js"></script>
<script type="text/javascript" ng-src="js/quiz.js"></script>
</head>
<body>
<div id="myQuiz" ng-controller="QuizController">
<h1>Test Your Knowledge: <span> Saturn</span></h1>
<div class="progress">
{{totalQuestions}}
</div>
</div>
</body>
</html>
quiz.js
(function(){
var app = angular.module('myQuiz', []);
app.controller('QuizController', ['$scope','$http','$sce',function($scope,$http, $sce){
$scope.score = 0;
$scope.activeQuestion = -1;
$scope.activeQuestionAnswered = 0;
$scope.percentage = 0;
$http.get('quiz_data.json').then(function(quizData){
$scope.myQuestions = quizData.data;
$scope.totalQuestions = $scope.myQuestions.length;
});
}]);
})();
quiz_data.json
[
{
"question" : "Saturn is the _______ planet from the Sun.",
"answers" : [
{ "id" : 0, "text" : "Fourth" },
{ "id" : 1, "text" : "Sixth" },
{ "id" : 2, "text" : "Second" },
{ "id" : 3, "text" : "Eighth" }
],
"correct" : 1
},
{
"question" : "Which image shows a close-up of Saturn?",
"answers" : [
{"id" : 0, "image" : "images/close_up_01.jpg" },
{"id" : 1, "image" : "images/close_up_02.jpg" },
{"id" : 2, "image" : "images/close_up_03.jpg" },
{"id" : 3, "image" : "images/close_up_04.jpg" }
],
"correct" : 3
},
{
"question" : "One year on Saturn is equivalent to how many years on Earth?",
"answers" : [
{"id" : 0, "text" : "12"},
{"id" : 1, "text" : "6"},
{"id" : 2, "text" : "29"},
{"id" : 3, "text" : "2"}
],
"correct" : 2
},
{
"question" : "What is the name of Saturn's largest moon?",
"answers" : [
{"id" : 0, "text" : "Hercules"},
{"id" : 1, "text" : "Europa"},
{"id" : 2, "text" : "Goliath"},
{"id" : 3, "text" : "Zeus"},
{"id" : 4, "text" : "Titan"},
{"id" : 5, "text" : "Triton"}
],
"correct" : 4,
"feedback" : "Though the names seem similar, Triton orbits the planet Neptune."
},
{
"question" : "Saturn is visible from Earth without a telescope",
"answers" : [
{"id" : 0, "text" : "True"},
{"id" : 1, "text" : "False"}
],
"correct" : 0
}
]
website 看起来与json的连接不起作用。不知道怎么解决。
提前致谢!
【问题讨论】:
-
看起来像什么都没有被渲染。控制台说什么?
-
在加载 java 脚本引用时不要使用
ng-src。相反,它应该只使用src属性,例如<script type="text/javascript" src="js/angular.min.js"></script><script type="text/javascript" src="js/quiz.js"></script>,我认为这不会解决任何问题,但看到并发表了评论。控制台有错误吗? -
这是错误:angular.min.js:87 XMLHttpRequest 无法加载文件:///C:/MAMP/htdocs/S3/portfolio_v2/quiz_data.json。跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https、chrome-extension-resource。
-
在您的计算机上安装 localhost 服务器。由于浏览器安全限制,无法从
file://协议发出 ajax 请求
标签: javascript angularjs json