简体   繁体   English

我无法使用AJAX从servlet检索responseText

[英]I can't retrieve responseText from servlet using AJAX

I have a servlet file called NewServlet.java . 我有一个名为NewServlet.java的servlet文件。 This servlet is called by my AJAX script to retrieve the response. 我的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 . XMLHttpRequest无法加载http:// localhost:8084 / WebApplication1 / NewServlet Origin null is not allowed by Access-Control-Allow-Origin Access-Control-Allow-Origin不允许使用原点null

NewServlet.java NewServlet.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 test.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. 谢谢。

That's on the browser side...the security model only allows AJAX requests to the same host/port that you fetched the page from. 那是在浏览器端...安全模型仅允许AJAX请求到您从中获取页面的同一主机/端口。 Make sure that you've fetched your page via the server (eg http://localhost:8084/test.html ) and not loaded it via the filesystem. 确保已通过服务器(例如http:// localhost:8084 / test.html )获取了页面,并且未通过文件系统加载页面。 Then you should be good to go...or at least continue debugging. 然后,您应该可以进行...或至少继续调试。 ;) ;)

This can indeed happen when the servlet runs on a different port than where the ajax request is coming from. 当servlet在与ajax请求所来自的端口不同的端口上运行时,确实会发生这种情况。 This violates the Same Origin Policy for ajax requests and thus the browser won't process the ajax response. 这违反了针对ajax请求的“ 相同来源策略 ”,因此浏览器将不会处理ajax响应。 Apart from hosting the servlet behind the same port, other solutions are to return JSONP instead or to let the servlet set the HTTP Access-Control headers. 除了将Servlet托管在同一端口后面之外,其他解决方案还包括返回JSONP或让Servlet设置HTTP Access-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 . 但是,您需要记住,这样, 每个人都可以通过Ajax访问您的servlet。 If the servlet returns sensitive information, then this is a security hole. 如果servlet返回敏感信息,则这是一个安全漏洞。 But if it does not and it is supposed to be a public webservice, then it's safe. 但是,如果没有,并且应该是公共 Web服务,那么它是安全的。

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();

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. 以我的经验,如果要使用ajax加载数据,请将请求发送到jsp文件,然后从该jsp文件获取响应文本。 it is a lot easier to handel. 这很容易处理。 see this example if you like 如果您喜欢,请参见此示例

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函数即可,例如在按钮click动作上: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类,方法是在jsp页面顶部添加<%page import =“”%>,例如:

<%@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 我希望它可以帮助您

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM