首页 > 解决方案 > ajax调用spring boot的Jquery Datatable问题

问题描述

我正在关注这个 jquery 插件https://medium.com/@gustavo.ponce.ch/spring-boot-jquery-datatables-a2e816e2b5e9

我在从支持(Java rest api)获取数据时遇到问题。

这是我的html

<table class="table table-striped table-hover table-fw-widget" id="table3">
    <thead>
      <tr>
       <th>ids</th>
       <th>user</th>
       <th>title</th>
       <th>body</th>
      </tr>
     </thead>
</table>

这是我的js代码,

<script>
$(document).ready( function () {
var table = $('#table3').DataTable({
             "bProcessing": true,
             "bServerSide": true,
             "ajax": {
                    "url": "/employees",
                    "dataSrc": ""
                },
               "aaData":"data",
                "order": [
                    [ 0, "asc" ]
                    ],
                "Columns": [
                      { "data": "Id"},
                      { "data": "Name" },
                      { "data": "lastName" },
                      { "data": "totalTime" },
                      { "data": "todaysDate" },
                      { "data": "taskDetails" }
                ]
         });
    });
    
    </script>

java中的后端控制器,

@RestController
public class TimeSheetAPI {
    
    @Autowired
    SomeService someService;
    
    
    @Autowired
    CredService cService;

    @RequestMapping(path="/employees", method=RequestMethod.GET)
    public List<Employee> getAllEmployees(Principal principal){
        Cred user = cService.findByUserName(principal.getName());
        List<Employee> employeedetails = someService.findEmployeeDetails(user);
        return employeedetails ;
    }
}

现在我用邮递员测试了我的api,它工作正常。但是当我在上面运行代码时,ajax 调用不起作用。

如果有更好的方法,我做错了什么然后请提及

标签: javaajaxspring-bootdatatablesthymeleaf

解决方案


问题出在您的网址中。尝试如下

<script th:inline="javascript">
/*<![CDATA[*/
    var ajaxUrl = /*[[ @{'/employees'} ]]*/;


$(document).ready( function () {
var table = $('#table3').DataTable({
             "bProcessing": true,
             "bServerSide": true,
             "ajax": ajaxUrl,
               "aaData":"data",
                "order": [
                    [ 0, "asc" ]
                    ],
                "Columns": [
                      { "data": "Id"},
                      { "data": "Name" },
                      { "data": "lastName" },
                      { "data": "totalTime" },
                      { "data": "todaysDate" },
                      { "data": "taskDetails" }
                ]
         });
    });
/*]]>*/
</script>

推荐阅读