javascript Servlet 对 AJAX 请求的响应为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5693457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Servlet response to AJAX request is empty
提问by Eric Lilja
I am sending an AJAX request using javascript to a servlet. The servlet is indeed replying but the response header is null and so is the response text.
我正在使用 javascript 向 servlet 发送 AJAX 请求。servlet 确实在回复,但响应标头为空,响应文本也是如此。
When I try the same client code to instead send the request to a php page it works fine.
当我尝试使用相同的客户端代码将请求发送到 php 页面时,它工作正常。
Here are the two clients (you can try them and look at their sources):
这是两个客户端(您可以尝试并查看它们的来源):
- ajax-to-servlet:
http://79.136.61.27/web/ajax-to-servlet.html - ajax-to-php:
http://79.136.61.27/web/ajax-to-php.html
- ajax-to-servlet:http:
//79.136.61.27/web/ajax-to-servlet.html - ajax-to-php:http:
//79.136.61.27/web/ajax-to-php.html
The output when sending the request to the servlet is:
将请求发送到 servlet 时的输出是:
Response will go below
Response:
responseText was null!
Headers:
null response headers!
The output when sending the request to PHP is:
向 PHP 发送请求时的输出是:
Response will go below
Response:
Hi from php
Headers:
Date: Sun, 17 Apr 2011 11:58:57 GMT Server: Apache/2.2.17 (Win32) PHP/5.3.6 X-Powered-By: PHP/5.3.6 Content-Length: 18 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: text/html
Here is the code for the servlet. As you can see I am experimenting a bit with settings headers and content type but none of my experiments seem to have any effect. The weird thing is, that I did a hello world-example like this using servlets just recently and it worked just fine without messing with headers and stuff. But now it just does not work anymore. :(
这是 servlet 的代码。正如您所看到的,我正在尝试设置标题和内容类型,但我的实验似乎都没有任何效果。奇怪的是,我最近使用 servlet 做了一个像这样的 hello world 示例,它工作得很好,没有弄乱标题和其他东西。但现在它不再起作用了。:(
package simple;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SimpleServlet extends HttpServlet {
private static final long serialVersionUID = -6713061702557291351L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String out = "<p>Hi from servlet!</p>";
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
System.out.println("got request");
PrintWriter pw = response.getWriter();
pw.write(out);
pw.flush();
boolean error = pw.checkError();
System.out.println("Error? " + error);
}
}
hifromphp.php is simply:
hifromphp.php 很简单:
<?php
echo "<p>Hi from php</p>";
?>
Thanks for reading and thanks in advance!
感谢您阅读并提前致谢!
Edit: I realized that those links will not work forever. So, for archive purposes I am pasting ajax-to-servlet.html here. ajax-to-php.html is identical except the URL where the request goes. ajax-to-html.html:
编辑:我意识到这些链接不会永远有效。因此,出于存档目的,我将 ajax-to-servlet.html 粘贴在这里。ajax-to-php.html 是相同的,除了请求去的 URL。ajax-to-html.html:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Send ajax</title>
</head>
<body>
<script type="text/javascript">
/* <![CDATA[ */
function getXMLHttp() {
var xmlHttp = new XMLHttpRequest();
return xmlHttp;
}
function sendAjax() {
var xmlHttp = getXMLHttp();
var divResp = document.getElementById("response");
var divHdrs = document.getElementById("responseHeaders");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var hdrs = xmlHttp.getAllResponseHeaders();
var resp = xmlHttp.responseText;
divHdrs.innerHTML = "<p>Headers:</p><p>" + (hdrs ? hdrs : "null response headers!<p>");
divResp.innerHTML = "<p>Response:</p>" + (resp ? resp : "<p>responseText was null!<p>");
}
}
xmlHttp.open("GET", "http://79.136.61.27:8080/SimpleServlet/SimpleServlet", true);
xmlHttp.send(null);
}
/* ]]> */
</script>
<p><input type="button" value="Send Ajax" onclick="javascript: sendAjax();"/></p>
<p>Response will go below</p>
<div id="response"></div>
<div id="responseHeaders"></div>
</body>
</html>
采纳答案by BalusC
If you call the servlet standaloneit works fine. However, the servlet runs on a different port than where the ajax request is coming from. This violates the Same Origin Policyfor ajax requests and thus the browser won't process the ajax response. Apart from hosting the servlet behind the same port, you need to return JSONPor set the HTTP Access-Control
headers.
如果您独立调用 servlet,它可以正常工作。但是,servlet 在与 ajax 请求来自的端口不同的端口上运行。这违反了ajax 请求的同源策略,因此浏览器不会处理 ajax 响应。除了在同一端口后托管 servlet,您还需要返回JSONP或设置HTTPAccess-Control
标头。
If you want to allow everyoneto use the servlet, set the following header:
如果要让每个人都可以使用 servlet,请设置以下标头:
response.setHeader("Access-Control-Allow-Origin", "*");
The information in the response headers from your links suggests that you're running Apache HTTPD and Apache Tomcat. It's good to know that you can connect Apache HTTPD to Apache Tomcat using Tomcat Connector, it may be more useful.
您链接的响应标头中的信息表明您正在运行 Apache HTTPD 和 Apache Tomcat。很高兴知道您可以使用Tomcat Connector将 Apache HTTPD 连接到 Apache Tomcat ,它可能更有用。