springboot+thymeleaf模板下使用Ajax异步添加页面的标签(解决thymeleaf使用Ajax难题)

简单介绍功能需求

想要做的是显示一个书籍信息的详细页面,页面加载完成后使用Ajax异步请求服务器获取当前书籍同类别的其他书籍信息,将这些同类别书籍的信息罗列到下面,如图所示:

thymeleaf跟jsp实现该功能的话有所不同

在jsp模板上可以使用EL表达式(<%request...%>)来可以完成ajax的url路径

而thymeleaf需要使用th:inline元素外还要使用thymeleaf的无标签[[]]元素

才能完成对ajax的url路径输入

 

以下是功能的实现说明

script标签中加入th:inline="javascript"

<script th:inline="javascript">
	//查询同一类的书籍信息
	$(function(){
		$.ajax({
			url:[[@{'/details/id/'+${book.bid}+'/btid/'+${book.btid.btid}}]],
			type:"post",
			success:function(data){
				$("#product_list").empty();
				$(data).each(function(index,b){
					$("#product_list").append("<div class=\"product\">\n" +
							"\t\t\t\t\t\t\t\t<div class=\"product-desc\">\n" +
							"\t\t\t\t\t\t\t\t\t<div class=\"product-img\">\n" +
							"\t\t\t\t\t\t\t\t\t\t<img class='product_img_size' src=\""+[[@{/}]]+"images/data/"+b.photopath +"\" class=\"img-responsive \" alt=\"\" />\n" +
							"\t\t\t\t\t\t\t\t\t</div>\n" +
							"\t\t\t\t\t\t\t\t\t<div class=\"prod1-desc\">\n" +
							"\t\t\t\t\t\t\t\t\t\t<h5><a class=\"product_link\" href=\""+[[@{/}]]+"/details/id/"+b.bid+"\">"+b.name+"</a></h5>\n" +
							"\t\t\t\t\t\t\t\t\t\t<p class=\"product_descr\">\n" +
							"\t\t\t\t\t\t\t\t\t\t\t<p>\n" +
							"\t\t\t\t\t\t\t\t\t\t\t\t<p style=\"text-indent:2em;\" class='content_product'>"+b.contentIntroduction+"</p>\n" +
							"\t\t\t\t\t\t\t\t\t</div>\n" +
							"\t\t\t\t\t\t\t\t\t<div class=\"clearfix\"></div>\n" +
							"\t\t\t\t\t\t\t\t</div>\n" +
							"\t\t\t\t\t\t\t\t<div class=\"product_price\">\n" +
							"\t\t\t\t\t\t\t\t\t<span class=\"price-access\">¥"+b.price+"</span>\n" +
							"\t\t\t\t\t\t\t\t\t<button class=\"button1\"><span>加入购物车</span></button>\n" +
							"\t\t\t\t\t\t\t\t</div>\n" +
							"\t\t\t\t\t\t\t\t<div class=\"clearfix\"></div>\n" +
							"\t\t\t\t\t\t\t</div>");
				});
			}
		});
	});
</script>

1、ajax的url使用thymeleaf的[[@{/xxx/xxx}]]来加上项目的路径

2、添加节点的中给img标签和a标签加上项目路径也可以使用[[@{/xxx/xxx}]]

3、第二点中如果不使用[[@{/xxx/xxx}]],就需要在Springboot项目中的application.properties文件里不要设置项目访问路径

例如:(这里是设置项目访问的)

server.servlet.context-path=/bookstore

实现效果:

如图所示,img标签和a标签的链接都成功加上了项目路径

Java后台代码:

 @PostMapping("/details/id/{bid}/btid/{btid}")
    @ResponseBody
    public List<Book> queryBookByBookType(@PathVariable(name="bid") Integer bid,@PathVariable(name="btid") Integer btid){
        System.out.println(bid+" "+btid);
        List bookList2=bookService.queryBooksByBtid(bid,btid);
        return bookList2;
    }

上面代码关于该功能的controller层请求方法代码

  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值