本文实现Ajax的局部刷新。思路如下:
首先,从JSP页面A.jsp向服务端发起一个Ajax请求,由Action中方法MethodA处理,该MethodA方法进行数据组装后,返回一个jsp页面Result.jsp,然后在Ajax的返回结果中,将Result.jsp元素,渲染到A.jsp中。
如图:
A.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html> <head> <Meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>TEST</title> <script type="text/javascript" src="/end/js/jquery-1.7.1.js"></script> <script type="text/javascript"> $(function() { $("#search").click(function() { $.ajax({ type : 'post',async : true,url : '/end/app/offlinerepay/offlineRepay.shtml?orderId=' + $("#orderId").val(),cache : false,success : function(data) { $("#id_ul").remove(); $("#id_total").empty(); $("#id_right").empty(); $("#id_left").prepend($(data).find("#id_ul")); $("#id_total").append($(data).find("#id_total")); $("#id_right").append($(data).find("#id_form")); } }); }); }) </script> </head> <body> <div class="container"> <div class="container-top" id="queryDiv"> <div class="search"> <input type="text" placeholder="输入订单号" id="orderId"> <button id="search">Search</button> </div> </div> <div id="id_left" class="container-left"> <div class="total" id="id_total"></div> </div> <div id="id_right" class="container-right"></div> </div> </body> </html>
Action类:
public class TestAction extends ActionSupport { private static final long serialVersionUID = -2577849709861478091L; private OrderService orderService; public String toOfflineRepay(){ return SUCCESS; } public String offlineRepay() throws Exception{ HttpServletRequest request = ServletActionContext.getRequest(); List<Order> osps = null; request.setAttribute("osps",osps); return SUCCESS; } }
Result.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <div class="container-left" id="id_left"> <ul id="id_ul"> <c:forEach items="${osps}" var="item" varStatus="status"> <li>${status.index} </li> </c:forEach> </ul> <div class="total" id="id_total"> <p> <span><b id="totalMoney">123</b></span> </p> </div> </div> <div class="container-right" id="id_right"> <form action="/aa/success.action" method="post" id="id_form"> <input type="hidden" id="orderId" name="orderId" value="${orderId}"/> <p> <button type="submit" onclick="javascript:submitForm();">确认</button> </p> </form> </div>
struts配置:
<package name="offlinerepay" extends="struts-base" namespace="/end/app/offlinerepay"> <action name="offlineRepay" class="offlineRepayAction" method="offlineRepay"> <result name="success">/WEB-INF/end/app/offlinerepay/result.jsp</result> </action> </package>
这样实现Ajax,好处多多,能够实现局部刷新页面。
原文链接:https://www.f2er.com/ajax/163482.html