如何使用 ajax 或 jquery 读取异步 HTTP (servlet3.0) 响应

How to read async HTTP (servlet3.0) response using ajax or jquery?

本文关键字:servlet3 响应 HTTP 异步 ajax 何使用 jquery 读取      更新时间:2023-09-26

我是javascript/ajax开发的新手。在我的应用程序中,我在服务器端使用 push servelt3.0,而客户端是 ajax 来读取推送消息(部分响应)。服务器不断通过 ServletOutputStream 推送消息,但在客户端,我使用 ajax 来读取异步 http 响应,这与在 java 中读取 steam 不同。我每次都收到附加的回复

阿贾克斯代码:

var a;
    if (window.XMLHttpRequest)
    {// If the browser if IE7+[or]Firefox[or]Chrome[or]Opera[or]Safari
      a=new XMLHttpRequest();
    }
   else
    {//If browser is IE6, IE5
      a=new ActiveXObject("Microsoft.XMLHTTP");
    }
a.onreadystatechange=function()
{
  console.log("a.readyState: " + a.readyState + " response is : " + a.response);
  if (a.readyState==4 && a.status==200)
  {
    console.log("state 4 response is : " + a.response);
    document.getElementById("myDiv").innerHTML=a.responseText;
  }
}
a.open("GET","http://localhost:8080/Servlet3Demo/AsyncLongRunningServlet?time=12000",true);
//a.multipart = true; 
a.overrideMimeType("Transfer-Encoding: chunked");
//a.overrideMimeType("text/plain");
a.send();
} 

响应是:

a.readyState: 3 response is : Fri Jan 30 11:40:45 IST 2015 ajaxTestPc.html:92
a.readyState: 3 response is : Fri Jan 30 11:40:45 IST 2015Fri Jan 30 11:40:46 IST 2015 ajaxTestPc.html:92
a.readyState: 3 response is : Fri Jan 30 11:40:45 IST 2015Fri Jan 30 11:40:46 IST 2015Fri Jan 30 11:40:47 IST 2015 

我想像java流一样阅读它。

请指教。

谢谢

嘿,我不知道

我的答案是否符合您的要求,但是而不是使用javascript,为什么您继续使用jQuery for ajax,因为它易于使用且编写得很好,代码行很短,例如:

$(document).ready(function(){
   $.ajax({
      data:'whatever data you want to use to send on url',
      type:'post / get',
      async: true,
      success: function(){
          // whatever on success you want to write
      },
      error: function(){
         // on ajax fail any message
      }
   })
})

像这样,ajax 有很多选项可以在这里阅读