【问题标题】:AJAX HttpRequest doesn't recieve updated data from servletAJAX Http 请求未从 servlet 接收更新的数据
【发布时间】:2015-05-07 10:37:54
【问题描述】:

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 时,第二个浮点数发生了变化,第一个浮点数是固定的。

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

【问题讨论】:

    标签: ajax http servlets browser-cache


    【解决方案1】:

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

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

    这只是让浏览器认为每个请求都是唯一的;无需在服务器端对该参数执行任何操作。

    或者,您可以在 Ajax 调用的 servlet 中添加无缓存标头。为了格外小心,您也可以同时这样做。

     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);
    

    【讨论】:

      猜你喜欢
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      相关资源
      最近更新 更多