从JavaScript访问Spring模型变量

Get access to Spring Model variable from JavaScript

本文关键字:模型 变量 Spring 访问 JavaScript      更新时间:2023-09-26

如何在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:each="category: ${categories}"),并有能力添加新的类别到类别变量,并设置其属性(id,名称,例如食谱)。那么,我如何在JavaScript中访问变量"类别",以及如何在JavaScript中添加新元素和设置属性?

您可以对该方法进行ajax调用

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

java method change

 @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);
}

了解更多关于ajax的信息

你必须创建一个API。比如休息。其思想是创建可被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;
}

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

使用Angular的JS代码片段:
$http.get('/app/get').then(function(response) {
        $scope.categoryList = response.data;
 }, function(response) {
});
$.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();
 }
}