解决的问题:当通过AJAX多次提交请求,而服务器端反映比较慢,导致只有最后一个请求被响应的现象。 首先 提供一个简单的ajax应用,包含两个jsp文件,一个提交请求,一个处理请求。 提交请求:ajaxtest.jsp <%@ page contentType="text/html; charset=GB2312" %>
ajaxtest
AJAX TEST
响应请求:ajaxtestresponse.jsp <%
String count = request.getParameter("count"); String ctime = request.getParameter("refreshtime"); try { Thread.sleep(5000); } catch (InterruptedException ex1) { } out.write("Hello world-" count "-" ctime);
%> 其中,提交请求包含一个技术参数,响应请求延迟5秒左右的时间,再返回请求,以表示系统延迟比较大。
在tomcat中运行http://localhost:8080/ajaxtest.jsp 点击按钮,发送请求,然后等待回应,假如在没有回应之前,连续点击按钮提交请求,虽然后台接收到了这些请求,但是由于对运行状态的判定,web浏览器只能接收到最后一个返回的响应。
为了让浏览器能够全部接受返回的信息,有两个办法: 1、将 // 确定发送请求的方式和URL以及是否同步执行下段代码 http_request.open("GET", url, true); 改为 http_request.open("GET", url, false); 表示等到响应接收到后,才能进行其它操作, 这样web浏览器发送请求后会有较长时间的停顿,影响客户体验,不好。
2、将 function refreshTable() { k = new Date(); send_request('ajaxtestresponse.jsp?count=' ( count) '&refreshtime=' k); } 改为 function refreshTable() { if(http_request){ if(http_request.readyState!=4) { window.setTimeout('refreshTable()',500); return; } } k = new Date(); send_request('ajaxtestresponse.jsp?count=' ( count) '&refreshtime=' k); } 增加状态判定,并进行延迟。 客户体验好。
|