AJAX实现前后端完全分离

匿名 (未验证) 提交于 2019-12-03 00:33:02

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!