javascript 我无法使用 AJAX 从 servlet 检索 responseText
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5781034/
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
I can't retrieve responseText from servlet using AJAX
提问by Searock
I have a servlet file called NewServlet.java
. This servlet is called by my AJAX script to retrieve the response.
我有一个名为NewServlet.java
. 我的 AJAX 脚本调用这个 servlet 来检索响应。
I have verified the servlet by testing it in a browser.
我已经通过在浏览器中测试验证了 servlet。
But when I call it from my AJAX script it gives me a blank responseText
and an error that says
但是当我从我的 AJAX 脚本中调用它时,它给了我一个空白responseText
和一个错误
XMLHttpRequest cannot load http://localhost:8084/WebApplication1/NewServlet. Origin null is not allowed by Access-Control-Allow-Origin
XMLHttpRequest 无法加载 http://localhost:8084/WebApplication1/NewServlet。Access-Control-Allow-Origin 不允许 Origin null
NewServlet.java
新的Servlet.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<option value='1'>one</option>");
out.println("<option value='2'>two</option>");
out.println("<option value='3'>three</option>");
out.println("<option value='4'>four</option>");
out.println("<option value='5'>five</option>");
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}
}
test.html
测试.html
<html>
<head>
<script language = "javascript">
var xmlDoc = 0;
var xhttp = 0;
function reciveData()
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // IE 5/6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = redirectUser;
xhttp.open("GET","http://localhost:8084/WebApplication1/NewServlet",true);
xhttp.send();
}
function redirectUser()
{
if (xhttp.readyState == 4)
{
log = 0;
xmlDoc = xhttp.responseText;
alert(xmlDoc);
}
}
</script>
</head>
<body onload="reciveData()">
</body>
</html>
Can some one point me in a right direction ?
有人能指出我正确的方向吗?
Thanks.
谢谢。
回答by stevevls
That's on the browser side...the security model only allows AJAX requests to the same host/port that you fetched the page from. Make sure that you've fetched your page via the server (e.g. http://localhost:8084/test.html) and not loaded it via the filesystem. Then you should be good to go...or at least continue debugging. ;)
那是在浏览器方面......安全模型只允许 AJAX 请求到您从中获取页面的同一主机/端口。确保您已通过服务器(例如http://localhost:8084/test.html)获取您的页面,而不是通过文件系统加载它。那么你应该很高兴......或者至少继续调试。;)
回答by BalusC
This can indeed happen when 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, other solutions are to return JSONPinstead or to let the servlet set the HTTP Access-Control
headers.
当 servlet 在与 ajax 请求来自的端口不同的端口上运行时,确实会发生这种情况。这违反了ajax 请求的同源策略,因此浏览器不会处理 ajax 响应。除了将 servlet 托管在同一端口之后,其他解决方案是返回JSONP或让 servlet 设置HTTPAccess-Control
标头。
response.setHeader("Access-Control-Allow-Origin", "*");
You however need to keep in mind that this way your servlet is by Ajax accessible to everyone. If the servlet returns sensitive information, then this is a security hole. But if it does not and it is supposed to be a publicwebservice, then it's safe.
但是您需要记住,这样您的 servlet 就可以通过 Ajax 被所有人访问。如果 servlet 返回敏感信息,则这是一个安全漏洞。但是如果它没有并且它应该是一个公共网络服务,那么它是安全的。
回答by Arun S
This will solve your issue..
// Ajax response
res.setContentType("text/javascript");
res.setCharacterEncoding("UTF-8");
res.setHeader("Cache-Control", "no-cache");
PrintWriter out = res.getWriter();
out.print("GRANTED");
out.close();
回答by MoienGK
in my experience, if you want to load data with ajax, send your request to a jsp file, and get your response text from that jsp file. it is a lot easier to handel. see this example if you like
根据我的经验,如果您想使用 ajax 加载数据,请将您的请求发送到一个 jsp 文件,然后从该 jsp 文件中获取您的响应文本。处理起来要容易得多。如果你喜欢,请看这个例子
EDITED<<
已编辑<<
========================== ajax_load.js :
========================== ajax_load.js :
var xmlhttp;
function loadAdminRight(category){
xmlhttp = GetXmlHttpObject();
if (xmlhttp == null) {
alert("Your browser does not support Ajax HTTP");
return;
}
var url = "load.jsp";
url = url + "?category="+category;
xmlhttp.onreadystatechange = getLoad;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function getLoad(){
if (xmlhttp.readyState == 4) {
document.getElementById("right_content").innerHTML = xmlhttp.responseText;
//or what you want to do
}
}
=========================== load.jsp :
============================ load.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String l_category = request.getParameter("category");
if(l_category.equals("article")){
out.write("You have choosen article category");
out.write("<br/>");
}
}else if(l_category.equals("news")){
out.write("You have choosen article category");
out.write("<br/>");
}
%>
and to make the ajax going you just need to call the .js function from where you want, for example on a button click action : onClick="loadAdminRight("article");"
为了让ajax运行,你只需要从你想要的地方调用.js函数,例如在按钮点击动作上:onClick="loadAdminRight("article");"
and you can import your java classes in a jsp file with adding <%page import="" %> to the top of your jsp page for example :
并且您可以在 jsp 文件中导入您的 java 类,例如将 <%page import="" %> 添加到您的 jsp 页面顶部:
<%@page import="com.omicc.classes.Article"%>
<%@page import="com.omicc.classes.Article"%>
write your own load.jsp file which handles the response, then use out.write in your jsp file to write the response text.
编写您自己的用于处理响应的 load.jsp 文件,然后在您的 jsp 文件中使用 out.write 来编写响应文本。
i wish it helps you
我希望它能帮助你