【问题标题】:Get access to Spring Model variable from JavaScript从 JavaScript 访问 Spring Model 变量
【发布时间】:2016-09-04 09:51:05
【问题描述】:

如何在 JavaScript 中访问变量(作为属性添加到我的控制器中的模型)以及如何使用它的属性?

我的模特:

public class Category {
    private Long id;
    private String name;
    private List<Recipe> recipes = new ArrayList<>();
}

我的控制器:

@RequestMapping(path = "/", method = RequestMethod.GET)
public String showAllCategories(Model model) {
    List <Category> categories = categoryService.findAll();
    model.addAttribute("categories", categories);
    return "index";
}

在我的网页上,我需要显示所有类别(没问题,使用 Thymeleaf th:each="category : ${categories}")并能够将新类别添加到类别变量并设置其属性(id、名称、食谱例子)。 那么,如何在 JavaScript 中访问变量“类别”,以及如何在 JavaScript 中添加新元素和设置属性?

【问题讨论】:

    标签: javascript java spring spring-mvc thymeleaf


    【解决方案1】:

    你可以对这个方法进行ajax调用

    // using jquery
     $.ajax({
        url:'/',
        success:function(response){
           // get the return pf the method here
           // can be assigned to any variable
        }
    

    java方法变化

     @RequestMapping(path = "/", method = RequestMethod.GET)
    public String showAllCategories(Model model) {
         //rest of code
        return (the value which which you want to assign to model property);
    }
    

    Explore more about ajax

    【讨论】:

      【解决方案2】:

      您必须创建一个 API。 Rest 例如。 想法是创建可由javascript调用的方法(例如通过AJAX),并执行您需要在java中执行的操作。

      这里有一些伪代码:

      @RequestMapping(path = "/addCategory", method = RequestMethod.GET)
      public boolean AddCategory(Model model) {
        //Do your logic to add category
      
        if (/*everything went good*/) return true;
        else return fale;
      }
      

      【讨论】:

        【解决方案3】:

        为什么要使用Model?,当你可以直接以JSON访问对象时:

        使用 Angular 的 JS 片段:

        $http.get('/app/get').then(function(response) {
                $scope.categoryList = response.data;
         }, function(response) {
        });
        

        使用 Jquery 的 JS 片段:

        $.ajax({
                url: "/app/get",
                type: 'GET',
                success: function(response) {
                var categoryList = response.data;
                console.log(categoryList);
              }
        });
        

        Java 代码片段:

        @RestController
        @RequestMapping
        public class Controller {
        
        @RequestMapping(path = "/get", method = RequestMethod.GET)
        public List <Category> showAllCategories() {
            return categoryService.findAll();
         }
        }
        

        【讨论】:

          猜你喜欢
          • 2011-10-22
          • 2018-06-28
          • 1970-01-01
          • 1970-01-01
          • 2011-12-29
          • 1970-01-01
          • 1970-01-01
          • 2011-08-25
          • 2017-06-03
          相关资源
          最近更新 更多