如何在springboot控制器中将json数据返回到javascript?

问题描述 投票:-1回答:1

如何将json数据返回到javascript,以便bootstrap-table可以使用它?(我想在javascript中初始化它)

我使用springboot作为我的后端,bootstrap设计我的html页面和bootstrap表来显示我的数据。当这个html页面完全加载时,应该使用来自控制器的json数据初始化这个bootstrap-table。

阻止我的是我不知道如何将json数据返回到javascript,因此bootstrap-table可以使用它。

在控制器中,如果我将模板作为字符串返回,则无法返回我的json数据,如果我返回json数据并添加@ResponseBody,我只是得到一个带有json字符串的页面,我无法访问我的模板,更不用说使用json了数据初始化引导程序表。

控制器的一些代码:

ArrayList<AISResponse> aisResponses = new ArrayList<AISResponse>();
AISResponse aisResponse = new AISResponse();
aisResponse.setAISPath(AISPath);
aisResponse.setTmID(tmID);
aisResponse.setTmName(tmName);
aisResponses.add(aisResponse);
model.addAttribute("aisResponses", aisResponses);
return "AIS/UI_AIS_Properties"

来自html页面的一些代码:

<table id="table" data-toggle="table" data-pagination="true"
        data-search="true" data-page-size="30">
        <thead>
            <tr>
                <th data-sortable="true">AISPath</th>
                <th data-sortable="true">TM Name</th>
                <th data-sortable="true">TM ID</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="r:${aisResponses}">
                <td th:text="${r.AISPath}"></td>
                <td th:text="${r.tmID}"></td>
                <td th:text="${r.tmName}"></td>
            </tr>
        </tbody>
    </table>

现在我使用Thymeleaf来迭代aisResponses,所以我可以在表格中显示我的数据。但我想通过直接将json数据返回到javascript来初始化javascript中的表,我认为这将使我的html页面更加清晰。

javascript spring-boot controller thymeleaf bootstrap-table
1个回答
0
投票

在这种情况下,您可以使用ModelAndViewModel。两者都用于在Spring MVC应用程序中定义模型。模型定义了模型属性的持有者,主要用于向模型添加属性。您的代码应如下所示。

@RestController
public class YourController{

    @GetMapping
    public ModelAndView getAisList(){

    ModelAndView   modelView = new ModelAndView ("AIS/UI_AIS_Properties");

    ArrayList<AISResponse> aisResponses = new ArrayList<AISResponse>();
    AISResponse aisResponse = new AISResponse();
    aisResponse.setAISPath(AISPath);
    aisResponse.setTmID(tmID);
    aisResponse.setTmName(tmName);
    aisResponses.add(aisResponse);

    modelView.addObject("aisResponses", aisResponses);
    return modelView;

        }             
    }
© www.soinside.com 2019 - 2024. All rights reserved.