Thymeleaf front-end and back-end value transfer page value and js value

Reference: Thymeleaf front-end and back-end value transfer page value and js value

    Thymeleaf and Javascript

              Thymeleaf tutorial (12) Using expressions in tags and js

Purpose:
The back-end passes the value to the front-end through the Model, and the
page displays the value through the Model to display the
js through the Model. The value is used as a variable

1. Backstage Controller

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

Note: Add the attribute message to the model

2. The page takes the value through the Model

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

3.js takes value through model

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

Note: th:inline must not be less in the script tag, usually different comments will be added before and after the value

4. If the front end needs to accept an object in JSON format, it must not directly pass the JSON string

It can be converted to JSON object using Fastjson

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 ;
 //         // Disable the reference object 
        optionStr = JSON.toJSONString(echartService.selectSelling(),
                                        SerializerFeature.PrettyFormat,
                                        SerializerFeature.DisableCircularReferenceDetect);
        log.info(optionStr);
//         modal.addObject("option",JSON.parseObject(optionStr));
         // Because the option received by ECharts must be a JSON object, and optionStr is a String object, it needs to be converted to a JSON object 
        model.addAttribute("option" , JSON.parseObject(optionStr));

        return "echart";
    }


}

5. When ajax calls a request, you can directly return a string in Json format, but declare the object as JSON in ajax

// js call java method reference: 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( "Get all functions of the user successfully" );
                console.log("result "+JSON.stringify(result));
                menuJson = result;
            },
            error: function (result, XMLHttpRequest, textStatus, errorThrown) {
                console.log( "Failed to get all functions of the user" );
                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());
                // Status 
                console.log(XMLHttpRequest.readyState);
                 // Error message 
                console.log(textStatus);
            }
        });
        return menuJson;
    }
// Ajax global variable assignment reference: https://blog.csdn.net/gzp444280620/article/details/70922224 
menuJson = getUserFunc();
The getUserAllFunction request is as follows:
@GetMapping("/getUserAllFunction")
@ResponseBody
public String getUserAllFunction(HttpSession session){
List<UserFuncEntity> list = new ArrayList<>();
...//略
//If there is a reference type, you need to forcefully remove the reference. The reference cannot be recognized in js. 
return JSON.toJSONString(menuList,SerializerFeature.DisableCircularReferenceDetect );
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324934059&siteId=291194637