ajax的分页有一个小问题,就是点击浏览器的后退按钮不会起到作用,咱们点击下一页的时候浏览器的地址也不会改变,借助html5的history api可以解决这个问题,就是history.pushState,有人叫他们pjax,!!管他呢,直接上代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>烟花</title>
</head>
<body>
<button id="1">1</button>
<button id="2">2</button>
<button id="3">3</button>
<button id="4">4</button>
<button id="5">5</button>
<div id="box"></div>
</body>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>
<script>
$('button').click(function () {
var state=new Object();
state.id=$(this).attr("id");
$.ajax({
type : 'GET', //这里可以换成 GET
url : '../pjax/pjax',
data : {
id: this.id,
},
success : function (response, stutas, xhr) {
$('#box').html(response);
history.pushState(state,state.id,"pjax.html?page="+state.id);
}
});
});
window.addEventListener("popstate",loadState,false);
function loadState(e){
//console.log("id="+e.state.id);
//alert(e.state.id);
$.ajax({
type : 'GET', //这里可以换成 GET
url : '../pjax/pjax',
data : {
id: e.state.id,
},
success : function (response, stutas, xhr) {
$('#box').html(response);
var state=new Object();
state.id=response;
document.title=e.state.id;
//history.pushState(state,state.id,"page="+state.id);
}
});
}
</script>
</html>
servlet是这样的:
package pjax;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class pjax
*/
public class pjax extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public pjax() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String account = request.getParameter("id");
PrintWriter out = response.getWriter();
out.print(account);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
项目在myeclipse中是这样的:,
运行之后显示如下截图: