AJAX响应问题 [英] Problem with AJAX responses

查看:127
本文介绍了AJAX响应问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题.我编写了一个Java Servlet,它可以响应来自我的JavaScript应用程序的Ajax请求.来自Java Servlet的答案是xml编码的消息.通常情况下一切正常,但是如果我发送太多"(我认为)Ajax请求,则可能会在一个Ajax响应中出现更多响应,结果是Firefox报错消息根文档后垃圾":例如:

I have the following problem. I programmed a java servlet, which responses to ajax requests from my javascript application. the answer from the java servlet is a xml encoded message. normally everything works well, but if I send "too much" (I think) Ajax reqeusts, it happens that more responses are within one ajax reponse, and as a consequence, firefox complains with the error message "junk after root document": e.g.:

<root>
 <node1></node1>
</root>

<root>
 <node1></node1>
</root>

,并且不允许这样做(在一封邮件中两次< root> ).为什么会这样?我一直认为,对于每个ajax调用,都会启动一个新的servlet实例.那是错的吗?

and that is not allowed (two times <root> in one message). Why does this happen? I always thought for each ajax call, a new servlet instance will be started. is that wrong?

推荐答案

早先的答案很正确-您的名为"writer"的PrintWriter成员变量就是问题所在.Tomcat(或任何其他servlet容器)可能有一个实例同时处理多个请求( ).这是servlet编程中出现问题的常见原因.

The earlier answer got it right - your PrintWriter member variable named "writer" is the problem. Tomcat (or any other servlet container) might have one instance handle more than 1 request at the same time. This is a common cause of problems in servlet programming.

这是Tomcat可能正在做的一些伪代码(即使它很容易引起问题, 在servlet中也是有效的和应有的):

Here's some pseudo-code of what Tomcat might be doing (which is valid and expected in servlets, even though it can easily cause problems):

Servlet servlet = new ServletTest();

// in thread 1:
servlet.doPost(request1, response1);

// in thread 2:
servlet.doPost(request2, response2);

因此request1和request2可能同时运行,并共享writer变量.如果request1设置了writer,然后request2设置了writer,然后request1编写了XML,然后request2编写了XML,那么您将获得问题中显示的输出.

So both request1 and request2 might be running at the same time, and sharing the writer variable. If request1 sets the writer, then request2 sets the writer, then request1 writes XML, then request2 writes XML, then you'll get the output you show in your question.

这篇关于AJAX响应问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆