简体   繁体   English

防止在表单提交后使用Thymeleaf片段,Ajax和Spring Boot重新加载

[英]Prevent reload after form submit with Thymeleaf fragments, Ajax and Spring boot

I've searched for a long time here but nothing helped. 我在这里搜索了很长时间,但没有任何帮助。

I have a Spring Boot application together with Thymeleaf Bootstrap and jQuery 我有一个Spring Boot应用程序以及Thymeleaf Bootstrap和jQuery

Application Layout 应用布局

In the application Layout The right menu is in The mqttCenter.html: 在应用程序布局中,右键菜单位于mqttCenter.html中:

<div class="panel panel-default panel-back">
    <div class="panel-body button-wrapper">                   
        <a type="button" onlick="showIotManagerFrag();"
           href="javascript:void(0);" class="btn btn-primary btn-block">IoT - Manager</a>
    </div>
</div>
<div id=deviceManager></div>

where the button opens a thymeleaf Fragment with ajax request and puts it into the upper shown deviceManager div element. 其中按钮打开带有ajax请求的百里香片段,并将其放入上方显示的deviceManager div元素。 This is the layout next to the navigationbar. 这是导航栏旁边的布局。 Because i realized with an ajax call theres no pagerefresh or direction to another page. 因为我意识到用ajax调用,所以没有页面刷新或指向另一页面的方向。

And here is the fragments.html: 这是fragments.html:

<div id="device-management" th:fragment="deviceManager" class="panel panel-default panel-back">
    <div class="panel-body">
        <div class="row">
            <div class="col-md-12">
                <h1 class="text-center">IoT - Manager:</h1>
            </div>  
        </div>
        <div class="row">
            <div class="col-md-5">
                <h3 class="text-center bottom-buffer">Fügen Sie ein neues IoT - Device hinzu:</h3>      
                <form  id="addDevice" name="addDevice" th:action="@{/users/addDevice}" th:object="${device}" method="post">
                    <div class="form-group">
                        <label class="control-label" for="name">Device - Name:</label>                          
                        <input type="text" class="form-control" id="firstName" th:field="*{name}" placeholder="Name eingeben">
                    </div>  
                    <div class="form-group">
                        <label class="control-label" for="name">Device - Typ:</label>
                        <select  class="form-control" id="sel1" th:field="*{type}">
                            <option th:each="deviceType : ${deviceTypes}" th:value="${deviceType.type_id}" th:text="${deviceType.type}"></option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="topic">MQTT - Topic:</label>                          
                        <input type="text" class="form-control" id="topic" th:field="*{topic}" placeholder="Topic eingeben">
                    </div>              
                     <div class="form-group">
                        <label class="control-label"for="description">Beschreibung:</label>
                        <textarea class="form-control" rows="5" id="description" th:field="*{description}" placeholder="Eine kurze Beschreibung"></textarea>
                    </div>                  
                    <div class="form-group">
                        <div class="col-md-12 text-center">
                            <button type="submit" class="btn btn-default button-width"><span class="glyphicon glyphicon-send"></span>  Hinzufügen</button>
                        </div>
                    </div>
                </form>
            </div>
            <div class="col-md-2"></div>
            <div class="col-md-5">
                <h3 class="text-center bottom-buffer">Löschen Sie ein vorhandenes IoT - Device:</h3>
                <form id="removeDevice" name="removeDevice" th:action="@{/users/removeDevice}" th:object="${device}" method="post">
                    <div class="form-group">
                        <label class="control-label" for="name">IoT - Device auswählen:</label>
                        <select class="form-control" id="sel1" th:field="*{name}">
                            <option th:each="deviceName : ${deviceList}" th:value="${deviceName.device_id}" th:text="${deviceName.name}"></option>
                        </select>
                    </div>
                    <div class="form-group">
                        <div class="col-md-12 text-center">
                            <button type="submit" class="btn btn-default button-width"><span class="glyphicon glyphicon-send"></span>Löschen</button>
                        </div>
                    </div>

                </form>
                <div id="device-submit"></div>
            </div>
        </div>
    </div>
</div>

This fragment is called from mqttCenter.html and is in a different file fragments.html. 该片段是从mqttCenter.html调用的,并且位于另一个文件fragments.html中。 The modelobjects are passed by the Ajax Controller Call. 模型对象由Ajax控制器调用传递。

So I want no refresh or redirect to other pages after the submit of the forms inside. 因此,在提交表单之后,我不希望刷新或重定向到其他页面。 I've looked on many ajax requests here like put forms into json and work with @ResponseBody and suitable Mediatypes in my Controller but nothing worked. 我在这里查看了许多ajax请求,例如将表单放入json并在Controller中使用@ResponseBody和合适的Mediatypes,但没有任何效果。

Teh Resopnsebody always redirected me to the Requestmapping url instead back to the ajax success Method. Reh Resopnsebody始终将我重定向到Requestmapping网址,而不是回到ajax成功方法。

Here a Code snippet from Controller und Ajax for form Submit. 这里是Controller und Ajax提交表单的代码段。

@RequestMapping(value = "/users/addDevice", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
        produces = MediaType.TEXT_PLAIN_VALUE) 
@ResponseBody
public String deviceSaving(@Valid @ModelAttribute("addDevice") AddDevice device, BindingResult bindingResult)
{
    do Stuff.
return "success- String"

and here Ajax Call in fragments.html: 在这里,fragments.html中的Ajax调用:

$(document).ready(function() 
{

      $('#addDevice').submit(function(event) 
      {

          var json = $('#addDevice').serialize();

        $.ajax({
            url: "addDevice",
            data: JSON.stringify(json),
            type: "POST",

            beforeSend: function(xhr) 
            {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },

            success: function(data) 
            {
                var respContent = typeof(data);
                console.log(respContent); 
                respContent += "<span>"
                respContent += smartphone + "</span>"

                $("#device-submit").html(respContent);         
            }
        });

    event.preventDefault();
  });

});

What i'm doing wrong? 我做错了什么? Thanks for help... 感谢帮助...

Make sure you don't see any error in the JavaScript console. 确保在JavaScript控制台中没有看到任何错误。 I think you should move the preventDefault line into very first place of the submit function. 我认为您应该将preventDefault行移到Submit函数的第一位。

 $(document).ready(function() {

    $('#addDevice').submit(function(event) {
        event.preventDefault();

        var json = $('#addDevice').serialize();

        $.ajax({
            url: "addDevice",
            data: JSON.stringify(json),
            type: "POST",

            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },

            success: function(data) {
                var respContent = typeof(data);
                console.log(respContent);
                respContent += "<span>"
                respContent += smartphone + "</span>"

                $("#device-submit").html(respContent);
            }
        });

    });
});

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM