JavaWeb项目,用ajax请求(不刷新页面)每隔一段时间请求后台json数据,实现实时更新数据需求

1、javascript前端jQuery代码:

/*动态加载工厂函数*/
    $(function(){
    /*实时查询信息*/
    realTimeQuery();
    });

/*实时信息*/

    function realTimeQuery(){
    $.ajax("realTime.do",{
 type:"post",
 data:{pageSize:$("#pageSize").val()},
 dataType:"json",
 success:function(data){        //参数data为后台获取的数据
    $(".log").remove();
               for(i in data.data){        //data.data指的是数组,i为数组的索引
                       var tr;

               tr=  ''+data.data[i].received+''+''+data.data[i].sourceIp+''+

                                       ''+data.data[i].sourceHostname+''+''+data.data[i].facility+''+

                                       ''+data.data[i].severity+''+''+data.data[i].origin+''+

                                       ''+data.data[i].tag+''+

                                       ''+data.data[i].message+'';

    if(i%2==0){
$("#table1").append(''+tr+'');
    }else{
$("#table1").append(''+tr+'');
    }
               }
},
error:function(){
console.log("实时信息,请求失败");
    clearTimeout(t);
    }
    });
       t=setTimeout('realTimeQuery()', 20000);//每隔20秒,查询一次。

    };

2、java后端代码:

/**
 * 信息处理控制层
 * @author Administrator
 *
 */
@Controller
public class SyslogController {
@Resource
private SyslogService syslogService;

        /**
* 实时信息展示
*/
@RequestMapping("/realTime.do")
public  String realTimeQuery(Integer pageSize,HttpServletRequest request,HttpServletResponse response){
//判断是否为登录用户
String userCode = (String)request.getSession().getAttribute("userCode");
if(userCode!=null&&userCode!=""){
//实时查询
Page page = new Page(1,pageSize,pageSize,"","","","","","","","");
List list = this.syslogService.getSyslogList(page);
//返回数据
JSONArray jsonArray = new JSONArray();
for(Syslog syslog:list){
JSONObject jsonLog = new JSONObject();
jsonLog.put("received", syslog.getReceived());
jsonLog.put("sourceIp", syslog.getSourceIp());
jsonLog.put("sourceHostname", syslog.getSourceHostname());
jsonLog.put("facility", syslog.getFacility());
jsonLog.put("severity", syslog.getSeverity());
jsonLog.put("origin", syslog.getOrigin());
jsonLog.put("tag", syslog.getTag());
jsonLog.put("message", syslog.getMessage());
jsonArray.add(jsonLog);
}
JSONObject result = new JSONObject();
result.put("data", jsonArray);
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json" );
PrintWriter wr = response.getWriter();
wr.write(result.toString());
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "/main.jsp";

}

}

3、web.xml配置文件


 
  DispatcherServlet
  org.springframework.web.servlet.DispatcherServlet
 
  contextConfigLocation
  classpath:applicationContext.xml
 

 

 
  DispatcherServlet
  *.do

你可能感兴趣的:(Java开发)