SSM專案中實現Ajax輪詢——定時的通過Ajax查詢服務端
阿新 • • 發佈:2019-01-22
輪詢(polling):客戶端按規定時間定時像服務端傳送ajax請求,伺服器接到請求後馬上返回響應資訊並關閉連線。
優點:後端程式編寫比較容易。
缺點:請求中有大半是無用,浪費頻寬和伺服器資源。例項:適於小型應用。
前端:
<div id="p" class="easyui-panel" title="我的訊息" style="width:248px;height:200px;" data-options="iconCls:'icon-ms',collapsible:true"> <span id="tongzhi" style="display:none; padding: 20px; color: red; font-size: 28px;"> 您有<a href="#"><strong id="tongzhi-content">0</strong></a>條客戶新訊息</span></div>
//訊息區域性定時重新整理 setTimeout(function(){ Push(); },200); setInterval(function(){ Push(); },3000); function Push(){ $.ajax({ type:"POST", url:"getsum.action?dt=" +new Date().getTime(),//why getTime and wont use data:{}, beforeSend:function(){}, success: function(data){ var obj=eval("("+data+")");//eval使用前要先加括號,才能得到完整的json資料 if(obj.msg!=0){ $("#tongzhi-content").html(obj.msg);//更新提示內容中的數量部分 $("#tongzhi").show();//訊息提示內容,整個部分都顯示出來 $('#p').panel('open').panel('refresh');}else{ $("#tongzhi").hide();//隱藏整個提示訊息部分 } } }); }
service類:
/**定時獲取訊息 * */ public int getAccount(Integer emp_id);
xml類:
<!--定時獲取訊息--> <select id="getAccount" parameterType="java.lang.Integer" resultType="java.lang.Integer"> SELECT count(*) FROM number WHERE num_telstate=0 AND num_state=1 AND emp_id=#{arg0}; </select>
controller類:
/** * 用來及時訊息推送 * @param request * @param response * @throws Exception */ @RequestMapping("getsum") public void getsum(HttpServletRequest request,HttpServletResponse response) throws Exception{ HttpSession session = request.getSession(); Employee emp= (Employee) session.getAttribute("user"); try { //獲取話務中待領取總數 int count=numberService.getAccount(emp.getEmp_id());StringBuffer json =new StringBuffer("{"); json.append("'msg':'"+count+"'"); json.append("}");// 構造json資料格式 PrintWriter out = response.getWriter(); out.write(json.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }