【jQuery】ajax异步请求实现动态加载表格

SpringBoot的一个短链接项目,把后端传输过来的list集合通过ajax异步请求渲染到前端

前端

<table id="url_table" class="table table-bordered no-footer dataTable">
    <thead>
        <tr>
            <th>Original Urlth>
            <th>Shorten Urlth>
            <th>Visitsth>
            <th>Last visited timeth>
        tr>
    thead>
    <tbody >
    tbody>
table>

js(核心部分)

<script>
    $(function (){
        $.ajax({
            method:"GET",
            url:"/show",
            success:function (res){
                $.each(res,function (k,v){
                    $("#url_table tbody").append(""+
                                                 ""+ v.longUrl +"" +
                                                 ""+ v.shortUrl +"" +
                                                 ""+ v.visits +"" +
                                                 ""+ v.lastVisitedTime +"" +
                                                 ""
                                                )
                })
            }
        })
   })
})
script>

controller

@GetMapping("/show")
@ResponseBody
public List<WholeUrl> record(HttpServletRequest req,HttpSession session){
    List<WholeUrl> list = new ArrayList<>();

    User user = (User) session.getAttribute("user");
    List<Url> urlList = service.selectByUserId(user.getId());

    //根据后缀拼接
    for (Url url : urlList) {

        String shortUrl = "";
        if (req.getServerPort() == 80 || req.getServerPort() == 443) {
            shortUrl = String.format("%s://%s/%s/%s",
                                     req.getScheme(), req.getServerName(), user.getPrefix(), url.getSuffix());
        } else {
            shortUrl = String.format("%s://%s:%s/%s/%s",
                                     req.getScheme(), req.getServerName(), req.getServerPort(), user.getPrefix(), url.getSuffix());
        }
        //封装为对象
        WholeUrl wholeUrl = new WholeUrl();
        wholeUrl.setUsername(user.getUsername());
        wholeUrl.setLongUrl(url.getLongUrl());
        wholeUrl.setShortUrl(shortUrl);
        wholeUrl.setVisits(url.getVisits());
        wholeUrl.setLastVisitedTime(url.getLastVisitedTime());
        list.add(wholeUrl);

    }
    return list;
}

效果

【jQuery】ajax异步请求实现动态加载表格_第1张图片

你可能感兴趣的:(JavaScript,jquery,ajax,javascript)