在web项目中为了减少服务器压力经常会用到异步刷新部分页面
‘
如图所示,在点击左侧的li标签或者按钮,右边动态的显示对应的内容而不刷新整个页面。
今天用SSH+jquery来实现此功能
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript"
src=" ${ pageContext.request.contextPath }/script/jquery/jquery-1.9.js"></script>
<script type="text/javascript"
src="${ pageContext.request.contextPath }/script/js/my.js"></script>
<style type="text/css">
.left {
width: 100px;
float: left;
border: red 1px solid;
height: 500px;
}
.right {
float: left;
border: red 1px solid;
height: 500px;
width: 500px;
}
.content {
width: 1000px;
height: 600px;
}
</style>
</head>
<body>
<div class="content">
<div class="left">
<ul>
测试
<li id="test">test1</li>
<li>test2</li>
<li>test3</li>
</ul>
</div>
<div class="right" id="right"></div>
</div>
</body>
</html>
界面:
现在要实现的就是点击左侧的test1,在右侧异步显示对应的页面
action:
package com.dust.action;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.dust.entity.Teacher;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
@Controller
@Scope("prototype")
public class TeacherAction extends ActionSupport {
public String show(){
System.out.println("run...");
Teacher t = new Teacher();
t.setName("123");
t.setGender("男");
t.setId(10L);
ActionContext.getContext().getValueStack().push(t);
return "show";
}
}
struts.xml
<package name="default" namespace="/" extends="struts-default">
<action name="tea_*" method="{1}" class="teacherAction">
<result name="show">/right.jsp</result>
</action>
</package>
right.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'right.jsp' starting page</title>
<style type="text/css">
</style>
</head>
<body>
<table>
<thead>
<tr>
<td> id</td>
<td> name</td>
<td> desc</td>
</tr>
</thead>
<tbody>
<tr>
<td><s:property value="id" /></td>
<td><s:property value="name" /></td>
<td><s:property value="gender" /></td>
</tr>
</tbody>
</table>
</body>
</html>
哦差点忘了,还有一个Teacher的实体类
public class Teacher {
private Long id;
private String name;
private String gender;
省略setter、getter方法
js
$(function(){
$("#test").click(function(){
$.ajax({
url:"tea_show.do",
dataType:"html",
type:"get",
success:function(data){
$("#right").html(data);
}
});
});
});
测试:
点击test1右侧显示: