现在的位置: 首页 > 综合 > 正文

highcharts与ajax的应用

2013年11月04日 ⁄ 综合 ⁄ 共 2180字 ⁄ 字号 评论关闭

当获取大数据量时,为了缓解浏览器的压力,以免造成页面停留,需要把后台的数据分批提取到页面。方法:

<1>前台js:

<script type="text/javascript">
  var lastdata = [];
  function showdata(beginid){
   
       $.ajax({
    
        type:'POST',//默认是GET
        url:'ajax.do',//设置数据传递的action
        cache:'false',//是否从浏览器缓存中请求信息
   data:'index='+beginid,
      dataType:'json',//预期从action接收的数据类型,还可以是xml(返回XML文档)、html(纯文本html)、script(纯文本Javascript)
       
       success:function(json){//请求成功调用success方法
         var e = [];//每次返回的100条记录
         var index = 0;//当前的记录数
         var total = 0;//总记录数
         
         //获取数据块
         $.each(json,function(i,n){
         
          if(i < 20){
           e.push(n);
          }else if(i==20){
           index = n;
          }else{
           total = n;
          }
         });
         
     lastdata = lastdata.concat(e);//合并两个数组
     //alert(lastdata);
         
        
         
         //根据返回的数据块画实时图
         $("#drugchart").load("highcharts/drugChart.jsp",function(){
     _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");
 }

抱歉!评论已关闭.