简体   繁体   中英

jquery.get and servlet

I want a servlet to process GET request and return a string.

Very simplified version is:

public class handlequery extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text");
        PrintWriter out = response.getWriter();
        out.println("videoid");
    }
}

But the return data (which I check as follows) in the callback is - object XML Document .

$.get("handleq", function(data, textStatus) {
    alert("Done, with the following status: " + textStatus + "." +
          " Here is the response: " + data);
});

Can someone tell me why data is object XML Document when I should get videoid ?

There is no such content type as just "text" as far as I know, so it probably defaults back to XML.

Change the line to:

response.setContentType("text/plain");

By itself, text is not a valid content type. I'd suggest you use text/html instead:

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("videoid");

And specify that content type in the client-side call to $.get() :

$.get("handleq", function(data, textStatus) {
    alert("Done, with the following status: " + textStatus
        + ". Here is the response: " + data);
}, "html");

The jquery documentation on get says:

The success callback function is passed the returned data, which will be an XML root element, text string, JavaScript file, or JSON object, depending on the MIME type of the response. It is also passed the text status of the response.

This implies that the format of the data returned by the servlet depends on the HTTP Content-Type of your response. The one you are setting, "text", is not a valid MIME type. Thus jQuery won't recognize this format and will interpret it as an XML Document on the Javascript side. The correct MIME type for what you want is "text/plain".

Try

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    out.println("videoid");
    out.close();
}

then you should receive "videoid" instead of an XML Document.

You should also hint at jQuery that you are receiving "text" rather than anything else in your response:

$.get("handleq", function(data, textStatus) {
    alert("Done, with the following status: " + textStatus + "." +
          " Here is the response: " + data);
}, "text");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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