当获取大数据量时,为了缓解浏览器的压力,以免造成页面停留,需要把后台的数据分批提取到页面。方法:
<1>前台js:
<script type="text/javascript">
var lastdata = [];
function showdata(beginid){
$.ajax({
type:'POST',//默认是GET
_yizheng = lastdata;
initChart();
});
//设置延迟时间
setTimeout(function(){
if(index < total){
showdata(index+20);//每次取20个数据
}else{
lastdata = [];//取完所有数据后,重置数据集
alert('game over');
}
},2000);
}
});
}
</script>
<2>后台action:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, InterruptedException {
response.setContentType("text/html;charset=utf-8");
String index = request.getParameter("index");// 当前记录id
int currentid = 0;// 当前返回的记录数下标
int total = 0;// 总记录数
if (!"".equals(index) && index != null) {
currentid = Integer.parseInt(index);
}
PrintWriter pw = response.getWriter();
List all = new ArrayList();
for (int i = 0; i < 100; i++) {
double num = Math.random() * 100;
all.add((int) num);
}
List each = new ArrayList();
for (int i = currentid-20; i < currentid; i++) {// 根据ajax传递的id将数据分块传递,每次取20个数据
if(currentid<=all.size()){
each.add(all.get(i));
}
}
JSONArray json = JSONArray.fromObject(each);// 转化成json对象
json.put(each.size(), currentid);// currentindex ->json
json.put(each.size() + 1, all.size());// total ->json
pw.println(json);
System.out.println("each json is "+json);
// pw.println(currentid);
return null;
// return new ActionForward("/ajax.jsp");
}