【发布时间】:2015-02-20 02:25:07
【问题描述】:
我是 angularjs 的新手,并开始尝试使用 angularjs 使用 RESTful Web 服务。 在我的 Spring MVC 应用程序中,我有一个控制器:
@Controller
@RequestMapping(value = "/exam/{examName}")
public class SomeController {
@Autowired
private QuestionService questionService;
@RequestMapping(value = "/{examId}", produces = "application/json; charset=UTF-8")
@ResponseBody
public String getExam(@PathVariable int examId) {
List<Question> questions = questionService.find(Question.class, "examId", examId);
return JSONUtil.convertObjectToJSON(questions); //A json array is returned
}
}
此控制器返回以下 JSON 数组:
[
{
"id": 1,
"examId": 2,
"text": "1. Eyniköklü sözlər cərgəsini müəyyənləşdirin.\r\n"
},
{
"id": 2,
"examId": 2,
"text": "2. Sait səslərə aid düzgün fikiriəri seçin.\r\n\n\n\n\n\n1. Hava axını ağız boşluğunda heç bir maneəyə rast gəlmir.\r\n"
},
{
"id": 3,
"examId": 2,
"text": "3. Asılı tərəfi əsl Azərbaycan sözü ilə ifadə olunmuş söz birləşmələrini göstərin.\r\n"
},
{
"id": 4,
"examId": 2,
"text": "4. \"Amma sən lap ağ elədin ha\" cümləsində köməkçi nitq hissələrini ardıcıllıqla göstərin.\r\n"
},
{
"id": 5,
"examId": 2,
"text": "5. Hansı söz birləşməsinin asılı tərəfi aşağıdakı sxemə uyğundur?\r\n"
}
]
这是我的 html 文件,它使用 angularjs 使用此 Web 服务:
<!DOCTYPE html>
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-controller="customersController">
<div ng-repeat="x in names">
{{ x.text }} <br>
</div>
</div>
<script>
function customersController($scope,$http) {
$http.get("http://localhost:8086/QuizNoqteAz/exam/abituriyent/2")
.success(function(response) {$scope.names = response;});
}
</script>
</body>
</html>
Web 服务工作正常,我已使用 Postman Rest Client 对其进行了测试。 Angular js 不工作。 html 文件生成一个空白页面,并且没有显示任何内容。
非常感谢任何帮助。
【问题讨论】:
-
您是否尝试过定义一个模块来存储控制器?
-
我是 angularjs 新手,还没有使用模块。我在这里使用的方法在 w3schools 中有描述:w3schools.com/angular/tryit.asp?filename=try_ng_customers_json 我只是不明白为什么我的 json 没有被 angularjs 解析。
-
您可以尝试在
$http.get中执行console.log(response)以查看实际返回的内容。 -
XMLHttpRequest 无法加载 localhost:8086/QuizNoqteAz/exam/abituriyent/2。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'null'。
-
您必须在 Spring MVC 上启用 CORS(跨源请求)。这是一个指南:spring.io/guides/gs/rest-service-cors
标签: json angularjs rest spring-mvc get