【问题标题】:ajax in Thymeleaf SpringMVC?Thymeleaf SpringMVC中的ajax?
【发布时间】:2021-01-11 23:23:08
【问题描述】:

如何在 Thymeleaf SpringMVC 中使用 AJAX 获取主页中的片段?

我有 Spring MVC 和 Thymeleaf 模板引擎。我是 Thymeleaf 的初学者。

我想知道如何使用 ajax 获取网站的一部分,了解如何向控制器发出简单的 Ajax 请求,结果只呈现模板的一部分(片段)。

我试图将片段 job.html 返回到 home.html

我不想使用 jquery 我想使用普通的 javascript。

我认为我需要使用首先克隆所需的 div 第二清空主 div 第三将克隆附加到主 div 中

这是我的控制器的样子

   @GetMapping("/generalization")
    public String selectSection(Model model) {
        List<DateasDto> section = generalizationService.getSection();
        model.addAttribute("section", section);
        return "home";
    }

    @GetMapping("/organisations/{id}/general")
    public String getGeneralSuccess(@PathVariable String id , Model model){
        List<AssessmentDto> gen = generalizationService.getGeneral(id);
        model.addAttribute("gen" , gen);
        return "Job";
    }

这是我的 html home.html 的样子

<body>
<script type="text/javascript" th:src="@{/js/working.js}"></script>

<form onsubmit="getGen(event)" >

    <div class="form-group" >
        <label for="SelectSection">Select Section</label>
        <select  class="form-control" id="SelectSection" onchange="sectionChangeSelected()">
        <option value="">Select section</option>
        <option th:each="section: ${section}"
                th:text="${section.name}"
                th:value="${section.id}"
        ></option>
        </select>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

<div id = "table" ></div>

<div th:replace = "Job.html :: myTable " ></div>
</body>

这里的js看起来像

    const getGen= (event) => {
        event.preventDefault()
        console.log("get assessment called")
        let id= document.getElementById("SelectSection").value;
        console.log(id)
        let url = `/org/subjects/${id}/assessments`
        fetch(url) 
        .then(function() {
            
        })
        .catch(function() {
            
        });
    }

这是我的 Job.html 的样子

<body>

<div th:fragment = "myTable" >
    <table>
            <thead>
                <tr>
                    <td >Name</td>
                    <td >Date</td>
                </tr>
            </thead>
            <tbody>
                <tr th:each="gen : ${gen}">
                    <td th:text="${gen.Name}"></td>
                    <td th:text="${gen.Date}"></td>
                </tr>
            </tbody>
    </table>
</div>

</body>

【问题讨论】:

    标签: javascript spring spring-mvc thymeleaf


    【解决方案1】:

    以下是在服务器端呈现 HTML 并在 Ajax 调用中异步返回的方法:在 ajax 调用中,您可以获取返回的 HTML 并附加到占位符 div。

        @GetMapping(value = "/theUrl")
        public String aMethod() {
            return "theFileName :: fragmentName "; //THIS
        }
    

    完整示例:

    弹簧控制器:

    @Controller
    class Ctrl {
        @GetMapping("/main")
        public String index() {
            return "mainPage";
        }
        @GetMapping(value = "/getMoreMessage")
        public String moreMessage(Model m) {
            m.addAttribute("msg", "Server time is " + ZonedDateTime.now());
            return "frag/ajaxPart :: time-info ";
        }
    }
    

    resources/templates/frag/ajaxPart.html中的片段:

    <div th:fragment="time-info" class="tooltip">
        <H2>Received from server:</H2>
        <span th:text="${msg}"></span>
    </div>
    

    '/main' 映射的 HTML 页面 - mainPage.html

    <!DOCTYPE HTML>
    <html>
    <body>
    
    <script>
        const getData = () => {
    
            fetch('getMoreMessage').then(function (response) {
                return response.text();
            }).then(function (html) {
                console.log(html)
                document.getElementById("myPlaceHolder").innerHTML += html;
            }).catch(function (err) {
                console.warn('Something went wrong.', err);
            });
        }
    
    </script>
    
    <p><input type="button" onclick="getData( )" value="Get Data"/></p>
    <div id="myPlaceHolder"></div>
    
    </body>
    </html>
    

    【讨论】:

    • 感谢@gtiwari,它帮助了我很多。我一般问有没有不使用javascript的方法我可以通过使用th:replace or th:insert来使用片段并且页面不应该刷新。
    • Thymeleaf 在服务器端执行渲染。您可以从服务器中提取数据而不刷新页面的唯一方法是使用 Ajax 调用。我的答案中的代码是使用 Ajax 操作。它不会刷新页面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    相关资源
    最近更新 更多