Thymeleaf前后端传值 页面取值与js取值

参考: Thymeleaf前后端传值 页面取值与js取值

    Thymeleaf 与 Javascript

              Thymeleaf教程 (十二) 标签内,js中使用表达式

目的: 
后端通过Model传值到前端 
页面通过Model取值显示 
js通过Model取值作为变量使用

1.后台Controller

@GetMapping("/message")
public String getMessage(Model model){
    model.addAttribute("message","This is your message");
    return "index";
}

注:向model中添加属性message

2.页面通过Model取值

<p th:text="#{message}">default message</p>

3.js通过model取值

<script th:inline="javascript">
    var message = [[${message}]];
    console.log(message);
</script>

注:script标签中 th:inline 一定不能少,通常在取值的前后会加上不同的注释

4.如果前端需要接受的是一个JSON格式的对象,一定不能直接传JSON字符串

可以使用Fastjson将其转换为JSON对象package springboot.echarts.controller;

复制代码
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;


import com.alibaba.fastjson.JSON;
import springboot.echarts.service.EchartService;

@Slf4j
@Controller
public class EchartsController {

    @Autowired
    private EchartService echartService;

    @GetMapping("/echart")
    public String echart(Model model){
        String optionStr  = null;
//        //禁用引用对象
        optionStr = JSON.toJSONString(echartService.selectSelling(),
                                        SerializerFeature.PrettyFormat,
                                        SerializerFeature.DisableCircularReferenceDetect);
        log.info(optionStr);
//        modal.addObject("option",JSON.parseObject(optionStr));
        //由于ECharts接收的option必须为JSON对象,optionStr为一个String对象,所以需要转为JSON对象
     //数组对象
//model.addAttribute("option",JSON.parseArray(optionStr));
model.addAttribute("option",JSON.parseObject(optionStr));
return "echart";
    }


}
复制代码

5.ajax调用请求时可以直接返回Json格式的字符串,但是在ajax中声明对象为JSON

复制代码
//js调用java方法参考:https://www.cnblogs.com/shirandedan/p/7727326.html
    var menuJson;
    function getUserFunc(){
        $.ajax({
            type: 'GET',
            url: "getUserAllFunction",
            cache: false,
            async : false,
            // headers : {
            //     'Content-Type' : 'application/json;charset=utf-8'
            // },
            // data: JSON.stringify(menuJson),
            dataType: 'json',
            success: function (result) {
                console.log("获取用户所有功能成功");
                console.log("result "+JSON.stringify(result));
                menuJson = result;
            },
            error: function (result, XMLHttpRequest, textStatus, errorThrown) {
                console.log("获取用户所有功能失败");
                console.log("result "+JSON.stringify(result));
                console.log("menuJson "+menuJson);
                console.log("JSON.stringify(obj) "+JSON.stringify(menuJson));
                // 状态码
                console.log(XMLHttpRequest.status);
                console.log(XMLHttpRequest.toLocaleString());
                // 状态
                console.log(XMLHttpRequest.readyState);
                // 错误信息
                console.log(textStatus);
            }
        });
        return menuJson;
    }
//Ajax全局变量赋值参考: https://blog.csdn.net/gzp444280620/article/details/70922224
menuJson = getUserFunc();
复制代码
getUserAllFunction请求如下:
@GetMapping("/getUserAllFunction")
@ResponseBody
public String getUserAllFunction(HttpSession session){
List<UserFuncEntity> list = new ArrayList<>();
...//略
//若出现引用类型,需要强制去掉引用,js中不能识别引用
return JSON.toJSONString(menuList,SerializerFeature.DisableCircularReferenceDetect );
}
原文地址:https://www.cnblogs.com/zhuyeshen/p/11435747.html