【问题标题】:Angularjs using Spring MVC RESTful Web serviceAngularjs 使用 Spring MVC RESTful Web 服务
【发布时间】: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 文件生成一个空白页面,并且没有显示任何内容。

非常感谢任何帮助。

【问题讨论】:

标签: json angularjs rest spring-mvc get


【解决方案1】:

要查看问题所在,您可以使用console.log(response) 将响应输出到控制台并查看浏览器的控制台。这将告诉您从服务器返回的内容。

请求中没有“Access-Control-Allow-Origin”标头 资源。因此不允许访问 Origin 'null'。

是因为服务器没有启用 CORS。 This指南会告诉你怎么做。

【讨论】:

    猜你喜欢
    • 2011-06-13
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 2015-10-23
    • 2014-03-22
    相关资源
    最近更新 更多