AJAX Http Request确实从servlet接收更新的数据

时间:2015-03-05 21:44:59

标签: ajax http servlets browser-cache

的Servlet

package world.hello;

import java.io.IOException;
import java.io.PrintWriter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import world.hello.MyMainClass;

public class TestServlet extends HttpServlet{

  private static final int BYTES_DOWNLOAD = 1024;  

    public void doGet(HttpServletRequest request, 
           HttpServletResponse response) throws IOException
           {

            response.setContentType("text/plain");      

            OutputStream os = response.getOutputStream();
            os.write(("hello world"+Double.toString(Math.random())).getBytes());
            os.flush();
            os.close(); 
 }        
       public void doPost(HttpServletRequest request, 
               HttpServletResponse response) throws IOException
               {

                doGet(request, response);
      }

}

HTML:

<html>
<body>
<script>
function myAjax()
{
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }

    xmlhttp.open("GET","RunQuery", false); 
    xmlhttp.send(); 

    document.getElementById("myText").innerHTML=xmlhttp.responseText + " " + xmlhttp.readyState.toString() + " " + xmlhttp.status.toString() ;
    document.getElementById("myText2").innerHTML=Math.random();

}

</script>
    <button id = "myButton" onclick = "myAjax()">click me</button>

    <div id = "myText"></div>
        <div id = "myText2"></div>
</body>
</html>

如果我直接在http://localhost:9070/test_web_project_1/RunQuery

访问servlet

每次刷新它时,我都会显示一个不同的随机浮点数。

当我在http://localhost:9070/test_web_project_1/myxjax.html运行HTML时,第二个浮动更改,第一个是固定的。

造成这种情况的原因是什么,我该如何解决?

1 个答案:

答案 0 :(得分:1)

没关系我之前说过的话...你的代码是同步的,因为你将async设置为false。您的问题只是浏览器缓存。您的ajax请求正在缓存中。您可以通过向请求添加带日期/时间的参数来欺骗浏览器不加载缓存,如:

var d = new Date();
xmlhttp.open("GET","RunQuery?ts="+d.getTime(), false); 

这只会让浏览器看到每个请求都是唯一的;在服务器端没有必要对该参数做任何事情。

或者,您可以在Ajax调用的servlet中添加no-cache标头。你也可以做到两件事要格外小心。

 response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
 response.setHeader("Pragma","no-cache"); //HTTP 1.0
 response.setDateHeader ("Expires", 0);