SpringBoot的一个短链接项目,把后端传输过来的list集合通过ajax异步请求渲染到前端
前端
<table id="url_table" class="table table-bordered no-footer dataTable">
<thead>
<tr>
<th>Original Url</th>
<th>Shorten Url</th>
<th>Visits</th>
<th>Last visited time</th>
</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("<tr>"+
"<td>"+ v.longUrl +"</td>" +
"<td>"+ v.shortUrl +"</td>" +
"<td>"+ v.visits +"</td>" +
"<td>"+ v.lastVisitedTime +"</td>" +
"</tr>"
)
})
}
})
})
})
</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;
}
效果