【问题标题】:How to read async HTTP (servlet3.0) response using ajax or jquery?如何使用 ajax 或 jquery 读取异步 HTTP (servlet3.0) 响应?
【发布时间】:2015-01-30 06:18:31
【问题描述】:

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

ajax 代码:

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 ajax servlets servlet-3.0


    【解决方案1】:

    嘿,我不知道我的答案是否符合您的要求,但不是使用 javascript,为什么您不使用 jQuery 进行 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 有很多选项,可以是read here

    【讨论】:

      猜你喜欢
      • 2011-12-30
      • 1970-01-01
      • 1970-01-01
      • 2014-01-16
      • 2016-10-27
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多