开发者

I can't retrieve responseText from servlet using AJAX

I have a servlet file called NewServlet.java. This servlet is called by my AJAX script to retrieve the response.

I have verified the servlet by testing it in a browser.

But when I call it from my AJAX script it gives me a blank responseText and an error that says

XMLHttpRequest cannot load http://localhost:8084/WebApplication1/NewServlet. Origin null is not allowed by Access-Control-Allow-Origin

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("<opti开发者_StackOverflow社区on 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>

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


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 Policy for 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 JSONP instead or to let the servlet set the HTTP Access-Control headers.

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 public webservice, then it's safe.


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

EDITED<<

========================== 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 :

<%@ 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");"

and you can import your java classes in a jsp file with adding <%page import="" %> to the top of your jsp page for example :

<%@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.

i wish it helps you


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜