使用Ajax的XMLHttpRequest()从Spring后端获取JSON数据来填充表格。

huangapple go评论90阅读模式
英文:

Populate table using Ajax XMLHttpRequest() with JSON data from Spring backend

问题

I can't provide the exact code translation here, but I'll provide the translated version of your content in Chinese as requested:

我正在构建一个Spring Boot项目,我已经在其中使用Thymeleaf来渲染我的视图。对于其中一个数据集,我想要更加炫酷,而不是在GET方法中返回带有数据的Thymeleaf模板(使用model.addAttribute()等),我想使用ResponseEntity以JSON格式返回数据集,并使用Ajax的XMLHttpRequest()对象将该数据集传递给我的视图。

不幸的是,当我访问所需的端点时,视图没有渲染,而是在屏幕上显示了JSON数据 - 我在某种程度上理解为什么会发生这种情况,但我想知道在这种情况下如何渲染视图。因此,我最亲切的请求是:你能给我一个提示,我应该如何处理这个问题,还能不能看一下我的带有Ajax的js文件是否看起来没问题。

所以也许首先让我们看看我如何使用Thymeleaf来做(它很好地工作,因为视图被渲染了):

@GetMapping("/auth/admin/guests")
public String getGuestsDashboard(Model model) {
    model.addAttribute("guests", guestService.getAllGuestsWithoutDetails());
    return "admin/manageguests";
}

我不想使用Thymeleaf,所以我当前的方式如下:

Spring Controller返回JSON格式的数据

@GetMapping("/auth/admin/guests")
public ResponseEntity<String> getAllGuests2() throws JsonProcessingException {
    List<GetGuestsDto> guests = guestService.getAllGuestsWithoutDetails();
    LOG.info("Guest list: {}: ", guests.toString());
    if (!guests.isEmpty()) {
        return ResponseEntity.status(HttpStatus.OK).body(toJson(guests));
    } else {
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
}

private String toJson(Object object) throws JsonProcessingException {
    return new ObjectMapper().writeValueAsString(object);
}

带有从Spring后端获取数据的函数的JavaScript脚本(guest-admin.js)
您是否也可以看一下模板字面量(反引号)。

let GuestAdminUtils = {

    getAllGuestsWithoutDetails: function () {

        let xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://localhost:8081/auth/admin/guests', true);

        xhr.onload = function () {
            if (this.status === 200) {
                let guests = JSON.parse(this.responseText);
                console.log(guests);
                let output = '';
                for (let i in guests) {
                    output +=
                        `<tr>
                            <td>${guests[i].id}</td>
                            <td>${guests[i].lastName}</td>
                            <td>${guests[i].firstName}</td>
                            <td>${guests[i].emailAddress}</td>
                            <td>${guests[i].active}</td>
                         </tr>`;
                }
                document.getElementById('guestTableBody').innerHTML = output;
            }
        };
        xhr.send();
    }
};
GuestAdminUtils.getAllGuestsWithoutDetails();

部分带有要填充表格的HTML视图(manageguests.html)
我已经将脚本附加在视图底部。

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">

<head th:replace="fragments/dashboardhead"></head>

<body>
    <div class="table-responsive">
        <table id="guestTable" class="table table-striped table-sm">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>LastName</th>
                    <th>FirstName</th>
                    <th>Email</th>
                    <th>Status</th>
                    <th>Delete</th>
                    <th>Deactivate account</th>
                </tr>
            </thead>
            <tbody id="guestTableBody">

            </tbody>
        </table>
    </div>

    <script src="/static/scripts/guest-admin.js"></script>
    <footer th:replace="fragments/footer"></footer>
</body>

</html>

所以,当我输入URL http://localhost:8081/auth/admin/guests 时,我只能在Web浏览器中看到JSON数据,而不是整个带有表格等的视图。

不知道我是否在思考得正确。

英文:

I'm building a Spring Boot project for which I've been using Thymeleaf to render my views. For one of the datasets I wanted to be more fancy and instead of returning the Thymeleaf template in GET method with data (using model.addAtribute() etc.), I'd like to return the dataset in JSON format using ResponseEntity and pass that data set to my view using Ajax XMLHttpRequest() object.

Unfortunately, when I enter my desired endpoint, the view doesn't render, but instead I get the JSON data displayed on the screen - I sort of understand why this happens, but wonder how I can render the view in that case. Therefore, here is my kindest request: Could you give me a hint how I should handle that + take a look on my js file with ajax if it looks all right.

So maybe first let's have a look how I would have done that with Thymeleaf (And it works fine, as the view renders):

    @GetMapping(&quot;/auth/admin/guests&quot;)
    public String getGuestsDashboard(Model model) {
        model.addAttribute(&quot;guests&quot;, guestService.getAllGuestsWithoutDetails());
        return &quot;admin/manageguests&quot;;
    }

I would like not to use Thymeleaf, so my current way is as follows:

Spring Controller returning data in JSON format

    @GetMapping(&quot;/auth/admin/guests&quot;)
    public ResponseEntity&lt;String&gt; getAllGuests2() throws JsonProcessingException {
        List&lt;GetGuestsDto&gt; guests = guestService.getAllGuestsWithoutDetails();
        LOG.info(&quot;Guest list: {}: &quot;, guests.toString());
        if(!guests.isEmpty()) {
            return ResponseEntity.status(HttpStatus.OK).body(toJson(guests));
        } else {
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }
    }

    private String toJson(Object object) throws JsonProcessingException
    {
        return new ObjectMapper().writeValueAsString(object);
    }

JavaScript script (guest-admin.js) with a function fetching data from the Spring backend*
Could you also please take a look on the JS template literals (backticks).

let GuestAdminUtils = {

    getAllGuestsWithoutDetails : function() {

        let xhr = new XMLHttpRequest();
        xhr.open(&#39;GET&#39;, &#39;http://localhost:8081/auth/admin/guests&#39;, true);

        xhr.onload = function() {
            if(this.status === 200) {
                let guests = JSON.parse(this.responseText);
                console.log(guests)
                let output = &#39;&#39;;
                for(let i in guests) {
                    output +=
                        `&lt;tr&gt;
                            &lt;td&gt;${guests[i].id}&lt;/td&gt;
                            &lt;td&gt;${guests[i].lastName}&lt;/td&gt;
                            &lt;td&gt;${guests[i].firstName}&lt;/td&gt;
                            &lt;td&gt;${guests[i].emailAddress}&lt;/td&gt;
                            &lt;td&gt;${guests[i].active}&lt;/td&gt;
                         &lt;/tr&gt;`;
                }
                document.getElementById(&#39;guestTableBody&#39;);
            }
        }
        xhr.send();
    }
}
GuestAdminUtils.getAllGuestsWithoutDetails();

Part of the html view (manageguests.html) with table to be populated
I have attached the srcipt at the bottom of the view.

&lt;!doctype html&gt;
&lt;html xmlns:th=&quot;http://www.thymeleaf.org&quot;&gt;

&lt;head th:replace=&quot;fragments/dashboardhead&quot;&gt;&lt;/head&gt;

&lt;body&gt;
             &lt;div class=&quot;table-responsive&quot;&gt;
                &lt;table id=&quot;guestTable&quot; class=&quot;table table-striped table-sm&quot;&gt;
                    &lt;thead&gt;
                    &lt;tr&gt;
                        &lt;th&gt;Id&lt;/th&gt;
                        &lt;th&gt;LastName&lt;/th&gt;
                        &lt;th&gt;FirstName&lt;/th&gt;
                        &lt;th&gt;Email&lt;/th&gt;
                        &lt;th&gt;Status&lt;/th&gt;
                        &lt;th&gt;Delete&lt;/th&gt;
                        &lt;th&gt;Deactivate account&lt;/th&gt;
                    &lt;/tr&gt;
                    &lt;/thead&gt;
                    &lt;tbody id=&quot;guestTableBody&quot;&gt;

                    &lt;/tbody&gt;
                &lt;/table&gt;
            &lt;/div&gt;


&lt;script src=&quot;/static/scripts/guest-admin.js&quot;&gt;&lt;/script&gt;
&lt;footer th:replace=&quot;fragments/footer&quot;&gt;&lt;/footer&gt;
&lt;/body&gt;
&lt;/html&gt;

So when I enter the URL http://localhost:8081/auth/admin/guests I only get the JSON data displayed in the web browser, not the entire view with table etc.

Wondering if I'm thinking correctly or not.

Update #1:

As the response to the questions - that is the json data I get. So basically, I enter the endpoint /auth/admin/guests and this is displayed in the browser - NOT in the console, but in the body.
I have also added console.log(guests) in the js file (inside the if-statement), but nothing is displayed in the console, so my data doesn't seem to be reaching the script, perhaps...

[{&quot;id&quot;:1,&quot;lastName&quot;:&quot;Brown&quot;,&quot;firstName&quot;:&quot;Andrew&quot;,&quot;emailAddress&quot;:&quot;andrew.brown@yahoo.com&quot;,&quot;active&quot;:true},{&quot;id&quot;:2,&quot;lastName&quot;:&quot;Smith&quot;,&quot;firstName&quot;:&quot;Michael&quot;,&quot;emailAddress&quot;:&quot;michael.smith@gmail.com&quot;,&quot;active&quot;:true}]

答案1

得分: 0

所以,在进行了更多研究之后,我决定以以下方式进行(并且它按预期工作!):

  1. 我添加了一个名为'getGuestsDashboard'的方法,它仅返回一个视图(URL:/auth/admin/guests)。
  2. 我还保留了'getAllGuests'方法来获取数据并返回JSON,但它可以通过URI:/auth/admin/guests/getall 进行访问,我在我的ajax部分调用了这个URI。
英文:

So, after more research I decided to do that the following way (and it works as desired!):

  1. I added a method 'getGuestsDashboard', which returns just a view (url: /auth/admin/guests)
  2. Also kept the 'getAllGuests' method fetching data and returning JSON, but that is available under the uri: /auth/admin/guests/getall, which I'm calling in my ajax part.

huangapple
  • 本文由 发表于 2020年8月16日 20:08:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63436708.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定