SpringBoot | Thymeleaf | 局部更新

建立一个实体类:

public class Fruit {
    int id;
    String name;

    public Fruit() {
    }

    public Fruit(int id, String name) {
        this.id = id;
        this.name = name;
    }
  
   //省略get和set方法       
}

 

建立一个控制类:

package org.project.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;


@Controller
public class FruitController {

    @RequestMapping("/fruit")
    public String fruit(Model model){
        return "fruit";
    }

    @RequestMapping("/fruit/detail")
    public String detail(Model model,int id) {

        List<Fruit> fruits = new ArrayList<>();

        if(id == 0) {
           String[] strings={"香蕉","苹果","凤梨","西瓜"};
           for(int i = 1; i <= strings.length; i++) {
               fruits.add(new Fruit(i,strings[i-1]));
           }
        } else if(id == 1) {
            String[] strings={"菠萝","草莓","西红柿","黑莓","百香果","葡萄"};
            for(int i = 1; i <= strings.length; i++) {
                fruits.add(new Fruit(i,strings[i-1]));
            }
        }
        model.addAttribute("fruits",fruits);
        return "fruit::fruit-list";
    }
}

  

前端代码:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thyleaf</title>
    <script type="text/javascript" src="/lib/jquery/1.9.1/jquery.min.js"></script>
    <script>
        function ceshi1() {
            $('#fruit-list').load("/fruit/detail?id=0");
        }
        function ceshi2() {
            $('#fruit-list').load("/fruit/detail?id=1");
        }
    </script>
</head>
<body>
    <button onclick="ceshi1()">测试1</button>
    <button onclick="ceshi2()">测试2</button>

    <div id="fruit-list" style="text-align: center;margin:0 auto; 900px" th:fragment="fruit-list">
        <table width="100%" border="1" cellspacing="1" cellpadding="0">
            <thead>
                <th>ID</th>
                <th>水果名</th>
            </thead>
            <tbody>
                <tr th:each="fruit : ${fruits}">
                    <td th:text="${fruit.id}"></td>
                    <td th:text="${fruit.name}"></td>
                </tr>
            </tbody>
        </table>
    </div>

</body>
</html>

  

 效果:

原文地址:https://www.cnblogs.com/jj81/p/10134859.html