servlet中设置响应方式
//set header response.addHeader("Access-Control-Allow-Origin", "*"); response.setContentType("text/html;charset=utf-8"); // parse req String reqJSON=StreamUtils.getStr(request.getReader()); // service IProductService ps = new ProductServiceImpl(); String respJson = ps.findAllRespJson(reqJSON); // resp response.getWriter().write(respJson);
jquery中ajax基本格式
function loadJson() { var reqJson = { "opr": "findAll" }; //parse req var reqJsonStr = JSON.stringify(reqJson); $.ajax({ async: false, type: "POST", url: "http://localhost:8080/store/products", data: reqJsonStr, dataType: "text" }).done(function(respJsonStr) { //parse resp var respJson = JSON.parse(respJsonStr); //add template var htmlTemp = template("dataTemplate", respJson); $("#div_product").append(htmlTemp); }).fail(function() { alert("fail"); }); }
框架引入
<!--jquery一定要放前面--> <script src="js/jquery-3.3.1.js"></script> <!--template engine--> <script src="js/template-web.js"></script>
模板容器
<div class="album py-5 bg-light" id="div_product"> <!--add template engine--> </div>
模板定义
<script id="dataTemplate" type="text/template"> {{each data value i}} <div class="card mb-4 box-shadow"> <img class="card-img-top" src={{value.pimage}} alt={{value.pimage}}> <p class="card-text">{{value.pdesc}}</p> </div> {{/each}} </script>
最终渲染
//add template var htmlTemp = template("dataTemplate", respJson); $("#div_product").append(htmlTemp);
文章来源: AJAX实现前后端完全分离