【问题标题】:How to return json data to javascript in a springboot controller?如何在springboot控制器中将json数据返回给javascript?
【发布时间】:2019-09-17 05:26:37
【问题描述】:

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

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

阻碍我的是我不知道如何将 json 数据返回到 javascript,以便引导表可以使用它。

在控制器中,如果我将模板作为字符串返回,我将无法返回我的 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】:

    在这种情况下,您可以使用 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;
    
            }             
        }
    

    【讨论】:

      猜你喜欢
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      • 2019-04-13
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多