Spring Boot Ajax post 表单与模型和百里香叶一起提交

Tru*_*rin 5 ajax jquery spring thymeleaf spring-boot

我有一个 spring boot 控制器,它返回一个视图,我想通过使用 ajax 端点来更改它,但同时使用 modelAttribute 从表单中获取值,然后在页面上发送一个或多个列表并迭代那些带有百里香叶的清单。这可能吗?这是控制器:

@RequestMapping(value="/search", method=RequestMethod.POST)
    @ResponseBody
    public String search(@ModelAttribute("specification") Specification specification, Model model) {

        List<SearchResultAutovit> list;

        list = scrapper.searchMethod(specification.getPrice,specification.getModel);

        if (list == null || list.isEmpty()) { 
            model.addAttribute("msg","Something"); 
        } else { 
            model.addAttribute("listaAutovit", list); 
        }
        return "?";
    }
Run Code Online (Sandbox Code Playgroud)

Ajax 请求:

$(".btn.btn-danger").on('click', {function fire_ajax_submit() {
    var str = $(".form-inline.justify-content-center").serialize();

    $.ajax({
        type:"post",
        data:str,
        url:"/search",
        async: false,
        dataType: "json",
        success: function(){
           alert("success");
        }
    });

}
Run Code Online (Sandbox Code Playgroud)

我不想从 ajax succes 部分操作页面,因为当模型被发送到页面时,我已经用 thymeleaf 这样做了。

Ala*_*ruz 5

因此,您想要的是使用请求接收 Thymeleaf 片段ajax。您可以通过更改以下代码并添加一个片段来实现此目的,您将在其中添加属性。我们将创建一个html名为 list 的文件,其中包含片段。

百里香叶片段

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<th:block th:fragment="list">
    <th:block th:if="${list != null}">
        <th:block th:each="iterator: ${list}">
            <!-- Do something -->
        </th:block>
    </th:block>
    <th:block th:if="${msg != null}">
        <p th:text=${msg}></p>
    </th:block>
</th:block>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

控制器

@RequestMapping(value="/search")
public String search(@ModelAttribute("specification") Specification specification, Model model) {

    List<SearchResultAutovit> list;

    list = scrapper.searchMethod(specification.getPrice,specification.getModel);

    if (list == null || list.isEmpty()) { 
        model.addAttribute("msg", "Error!");
        model.addAttribute("list", list);
    } else { 
        model.addAttribute("list", list);
        model.addAttribute("msg", null);
    }
    return "layouts/list :: list";
}
Run Code Online (Sandbox Code Playgroud)

然后,ajax您只需接收结果并将其附加到元素中即可。

$.ajax({
    type:"post",
    data:str,
    url:"/search",
    dataType: "json",
    success: function(result){
       $(element).append(result);
    }
});
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。