春天和百里香叶的Ajax部分刷新后方法

Mon*_*ska 6 javascript ajax jquery spring-mvc thymeleaf

我无法部分更新我的页面。我用几句话解释业务问题。我有一个用户个人资料,他可以在其中更改有关他自己的任何信息:技能,个人信息,主要照片库。一切正常,但添加了等照片后,我的整个页面刷新了,这是我的烦恼。

首先,我显示添加主照片的确切位置

<div th:fragment="photoDiv">
    <img id="mainPhoto" th:src="@{/profile/main/img}" alt=""/>
    <div>
        <form id="mainPhotoForm" action="#" th:action="@{/profile/main/upload}"
              enctype="multipart/form-data" method="post">
            <label for="files"><img src="../../img/plus.png"/> Upload photo</label>
            <input id="files" style="display:none;" type="file" accept="image/*" th:name="img"
                   onchange="document.getElementById('mainPhotoForm').submit();"/>
        </form>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我的控制器

@PostMapping("/profile/main/img")
public String uploadingMianPhoto(@RequestParam("img") MultipartFile file,
                                 @ModelAttribute("userDto") userDto user) {
    String path = filesStrorage.storeFiles(file, getCurrentUserID());
    if (!path.isEmpty()) {
        Photo mainPhoto = new Photo();
        mainPhoto.setFileName(file.getOriginalFilename());
        mainPhoto.setPath(path);
        user.setProfilePhoto(mainPhoto);
    }
    return "/profile/edit";
}

// Load main photo
@RequestMapping(value = "/profile/main/upload")
public @ResponseBody
byte[] mainPhotoResponse(@ModelAttribute("userDto") UserDto user) throws IOException {
    Path path = Paths.get(user.getProfilePhoto().getPath());
    return Files.readAllBytes(path);
}
Run Code Online (Sandbox Code Playgroud)

我只想更新th:fragment="photoDiv"而不是整个页面。

我尝试过ajax片段更新,但是我不使用spring webflow,我应该添加spring webflow配置还是可以通过jquery做到这一点?

所以经过尝试

我添加了uploadingMianPhoto,return "/profile/edit :: photoDiv"但它只返回了整个页面上的这个片段

请给我一些ajax post功能实例,女巫一些解释词

Jak*_*Ch. 5

是的,您可以通过jQuery完成此操作。我能够做到,但是需要一些额外的JavaScript工作。我将通过一个简单的例子展示如何解决这种情况的一般思路。

首先,让我们假设我们有一些要传输的对象。没什么特别的。

SomeDto.java

public class SomeDto {

    private String fieldA;
    private String fieldB;

    // Getters and Setters
}
Run Code Online (Sandbox Code Playgroud)

其次,让我们使用一些具有post功能的标准控制器来执行此操作。我比平时添加“额外”的两件事是接受json请求正文内容并返回片段。

SomeController.class

@RequestMapping(path = "/some/endpoint", 
                method = ReqestMethod.POST, 
                consumes = "application/json; charset=utf-8")
public String postSomeData(@RequestBody SomeDto someDto) {

    // some action on passed object

    return "some/view :: some-fragment"
}
Run Code Online (Sandbox Code Playgroud)

然后,我们有了一个带有片段的html文件。这里的窍门是我们通过jQuery ajax异步发布数据,等待响应并用该响应替换片段(因为我们应该收到重新渲染的片段)。

some / view.html

<!-- Provide id to your fragment element, so that it can be referenced from js -->
<div id="some-fragment" th:fragment="some-fragment">

    <!-- Some rendered data. Omitted -->

    <!-- 
        Don't provide neither action nor method to form,
        cause we don't want to trigger page reload 
    -->
     <form>
        <label for="fieldA">Some field</label>
        <input id="fieldA" type="text" /><br />
        <label for="fieldA">Some field</label>
        <input id="fieldA" type="text" /><br />

        <!-- onclick calls function that performs post -->
        <button type="button" onclick="performPost()">Submit</button>
     </form>
</div>

<!-- 
    Script with logic of ajax call. Should be outside updated fragment.
    Use th:inline so that you could take advantage of thymeleaf's data integrating
-->
<script th:inline="javascript">

    performPost = function() {

        /* Prepare data that have to be send */
        var data = {};
        data.fieldA = $('#fieldA').val();
        data.fieldB = $('#fieldB').val();

        /* Prepare ajax post settings */
        var settings = {

            /* Set proper headers before send */ 
            beforeSend: function(xhr, options) {

                /* Provide csrf token, otherwise backend returns 403. */
                xhr.setRequestHeader("X-CSRF-TOKEN", [[ ${_csrf.token} ]]);

                /* Send json content */
                xhr.setRequestHeader("content-type" ,"application/json; charset=utf-8");
            },
            type: 'POST',
            url: [[ @{/some/endpoint} ]],
            data: JSON.stringify(data)
        }

        /* Send request to backend with above settings and provide success callback */
        $.ajax(settings).done(function(result) {

            /* 
                Replace your fragment with newly rendered fragment. 
                Reference fragment by provided id
            */
            $('#some-fragment').html(result);
        });
    }

</script>
Run Code Online (Sandbox Code Playgroud)

就这样。希望这对您有所帮助。如果有时间,我将尝试使用您的用例检查此解决方案并更新答案。