基于$.ajax()方法从服务器获取json数据的几种方式(4)
2、$.ajax()参数中设置dataType="json",则jquery会自动将返回的字符串转化为json对象。后台可以设置为:【推荐】response.setContentType("text/html;charset=utf-8");或者response.setContentType("application/json;charset=utf-8");
//Java代码:后台获取单个数控定位器的历史表格的数据 public void getHistorySingleData() throws IOException{ HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); response.setHeader("Content-type", "text/html;charset=UTF-8"); response.setContentType("text/html;charset=utf-8"); String deviceName = request.getParameter("deviceName"); String startDate= request.getParameter("startDate"); String endDate = request.getParameter("endDate"); SingleHistoryData[] singleHistoryData = chartService.getHistorySingleData(deviceName,startDate, endDate); System.out.println(singleHistoryData.length); System.out.println(JSONArray.fromObject(singleHistoryData).toString());//打印:[{"time":"2016-11-11 10:00:00","state":"运行","ball":"锁紧",....},{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....},{},{}....]查到几条singleHistoryData对象就打印几个对象的信息{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....} response.getWriter().print(JSONArray.fromObject(singleHistoryData).toString()); }
/*js代码:页面首次加载时,显示规定时间段的数据*/ var data1 = []; var deviceName=$("body").attr("id"); var startDate = $("#startDate").val("2000-01-01 00:00:00"); var endDate = $("#endDate").val("2018-01-01 00:00:00"); $.ajax({ url:"/avvii/chart/getHistorySingleData", type:"post", data:{ "deviceName":deviceName, "startDate": "2000-01-01 00:00:00", "endDate": "2018-01-01 00:00:00" }, dataType:"json", success: function (data) { alert(data);//---->弹出[object Object],[object Object],[object Object][object Object],[object Object],[object Object]……后台传过来几条singleHistoryData对象就打印几个json对象:[object Object] for(var i = 0; i < data.length; i++){ var name = data[i]['time']; var state = data[i]['state']; var ball = data[i]['ball']; var xd = data[i]['xd']; var yd = data[i]['yd']; var zd = data[i]['zd']; var xf = data[i]['xf']; var yf = data[i]['yf']; var zf = data[i]['zf']; data1[i] = {name:name,state:state,ball:ball,xd:xd,yd:yd,zd:zd,xf:xf,yf:yf,zf:zf}; } if(data.length != 10){ for(var j=0;j<(10-((data.length)%10));j++){ //补全最后一页的空白行,使表格的长度保持不变 data1[j+data.length] = {name:" ",state:"",ball:"",xd:"",yd:"",zd:"",xf:"",yf:"",zf:""}; } } var userOptions = { "id":"kingTable", //必须 表格id "head":["时间","运行状态","球头状态","X向位置/mm","Y向位置/mm","Z向位置/mm","X向承载力/Kg","Y向承载力/Kg","Z向承载力/Kg"], //必须 thead表头 "body":data1, //必须 tbody 后台返回的数据展示 "foot":true, // true/false 是否显示tfoot --- 默认false "displayNum": 10, //必须 默认 10 每页显示行数 "groupDataNum":6, //可选 默认 10 组数 sort:false, // 点击表头是否排序 true/false --- 默认false search:false, // 默认为false 没有搜索 lang:{ gopageButtonSearchText:"搜索" } } var cs = new KingTable(null,userOptions); } });
内容版权声明:除非注明,否则皆为本站原创文章。