Jetty servlet respons to Ajax always empty

Posted by chris on Stack Overflow See other posts from Stack Overflow or by chris
Published on 2010-05-12T09:27:27Z Indexed on 2010/05/12 22:54 UTC
Read the original article Hit count: 196

Filed under:
|
|
|
|

Hi I try to run a java server on Jetty which should respond to an ajax call. Unfortunately the response seems to be empty when I call it with ajax. When I call http://localhost:8081/?id=something I get an answer.

The Java Server:

   public class Answer extends AbstractHandler
{
    public void handle(String target,
                       Request baseRequest,
                       HttpServletRequest request,
                       HttpServletResponse response) 
        throws IOException, ServletException
    {
        String id = request.getParameter("id");
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");

        response.setContentLength(19+id.length());
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write("<message>"+id+"</message>");
        //response.setContentType("text/html;charset=utf-8");

        response.flushBuffer();
        baseRequest.setHandled(true);
    }

    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8081);
        server.setHandler(new Answer());

        server.start();
        server.join();
    }
}

The js and html:

<html>
<head>
<script>
var req;

function validate() {
   var idField = document.getElementById("userid");
   var url = "validate?id=" + encodeURIComponent(idField.value);
   if (typeof XMLHttpRequest != "undefined") {
       req = new XMLHttpRequest();
   } else if (window.ActiveXObject) {
       req = new ActiveXObject("Microsoft.XMLHTTP");
   }
   req.open("GET", "http://localhost:8081?id=fd", true);
   req.onreadystatechange = callback;
   req.send(null);
}


function callback() {
    if (req.readyState == 4) {
        if (req.status == 200) {
             var message = req.responseXML.getElementsByTagName("message")[0];
             document.getElementById("userid").innerHTML = "message.childNodes[0].nodeValue";
        }
    }
}

</script>
</head>
<body onload="validate('foobar')">
<div id="userid">hannak</div>
</body>
</html>

I'm actually don't know what I'm doing wrong here. Maybe someone has a good idea.

greetings chris

© Stack Overflow or respective owner

Related posts about jetty

Related posts about java