本文實現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,好處多多,能夠實現局部重新整理頁面。
這種方式是用於:請求頁面大部分重新整理,返回內容較多的情況。