Thymeleaf SpringMVC中的ajax? [英] ajax in Thymeleaf SpringMVC?

查看:50
本文介绍了Thymeleaf SpringMVC中的ajax?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想知道如何使用 ajax 获取网站的一部分,了解如何对控制器执行简单的 Ajax 请求,并在结果中仅呈现模板(片段)的一部分.

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

我不想使用 jquery 我想使用普通的 vanilla javascript.

我想我需要使用第一个克隆所需的 div 第二个清空主 div 第三个将克隆附加到主 div

这是我的控制器的样子

 @GetMapping("/generalization")公共字符串选择部分(模型模型){Listsection = generalizationService.getSection();model.addAttribute("section", section);返回家";}@GetMapping("/organisations/{id}/general")public String getGeneralSuccess(@PathVariable String id , Model model){Listgen = generalizationService.getGeneral(id);model.addAttribute(gen", gen);返回工作";}

这是我的 html home.html 的样子

<script type="text/javascript";th:src=@{/js/working.js}"></script><form onsubmit="getGen(event)";><div class="form-group";><label for="SelectSection">选择部分</label><select class="form-control";id=选择部分"onchange="sectionChangeSelected()"><option value="">选择部分</option><option th:each="section: ${section}";th:text="${section.name}";th:value="${section.id}";></选项></选择>

<按钮类型=提交"class=btn btn-primary">提交</button></表单><div id = 表格"></div><div th:replace = "Job.html :: myTable "></div>

这里的js看起来像

 const getGen= (event) =>{event.preventDefault()console.log(获取被调用的评估")让 id= document.getElementById(SelectSection").value;控制台日志(ID)让 url = `/org/subjects/${id}/assessments`获取(网址).then(function() {}).catch(函数(){});}

这是我的 Job.html 的样子

<div th:fragment = myTable"><表格><头><tr><td >姓名</td><td >日期</td></tr></thead><tr th:each="gen : ${gen}"><td th:text=${gen.Name}"></td><td th:text=${gen.Date}"></td></tr></tbody>

解决方案

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

 @GetMapping(value = "/theUrl")公共字符串 aMethod() {返回文件名::片段名";//这个}

完整示例:

弹簧控制器:

@Controller类 Ctrl {@GetMapping("/main")公共字符串索引(){返回主页";}@GetMapping(value = "/getMoreMessage")公共字符串 moreMessage(Model m) {m.addAttribute("msg", "服务器时间是" + ZonedDateTime.now());返回frag/ajaxPart :: 时间信息";}}

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

<H2>从服务器接收:</H2><span th:text="${msg}"></span>

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

<身体><脚本>const getData = () =>{fetch('getMoreMessage').then(function (response) {返回 response.text();}).then(函数(html){控制台日志(html)document.getElementById("myPlaceHolder").innerHTML += html;}).catch(函数(错误){console.warn('出了点问题.', err);});}<p><输入类型=按钮"onclick="getData()";value=获取数据"/></p><div id="myPlaceHolder"></div></html>

How to get fragment in main page using AJAX in Thymeleaf SpringMVC?

I am having Spring MVC and Thymeleaf templating engine. I'm a beginner in Thymeleaf.

I was wondering how can i use ajax to get part of website on how to do simple Ajax request to controller and in result rendering only a part of a template (fragment).

I was trying to return the fragment job.html into home.html

I don't want to use jquery I want to use plain vanilla javascript.

I think i need to use First clone the desired div Second empty the main div Third append the clone into the main div

Here is how my controller look like

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

Here is how my html home.html look like

<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>

here js look like

    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() {
            
        });
    }

here is how my Job.html look like

<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>

解决方案

Here's how you can render an HTML on the server side and return asynchronously on Ajax call: In your ajax call you can grab the returned HTML and append to a placeholder div.

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

Full example:

The Spring Controller:

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

The fragment in resources/templates/frag/ajaxPart.html:

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

HTML page for '/main' mapping - 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>

这篇关于Thymeleaf SpringMVC中的ajax?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆