繁体   English   中英

jquery.get 和 servlet

[英]jquery.get and servlet

我想要一个 servlet 来处理 GET 请求并返回一个字符串。

非常简化的版本是:

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");
    }
}

但是回调中的返回data (我检查如下)是 - object XML Document

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

有人可以告诉我为什么 data 是object XML Document什么时候我应该得到videoid

据我所知,没有像“文本”这样的内容类型,所以它可能默认回到 XML。

将行更改为:

response.setContentType("text/plain");

就其本身而言, text不是有效的内容类型。 我建议您改用text/html

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

并在对$.get()的客户端调用中指定该内容类型:

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

get上的 jquery 文档说:

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. 它还传递了响应的文本状态。

这意味着 servlet 返回的数据格式取决于响应的 HTTP Content-Type。 您设置的“文本”不是有效的 MIME 类型。 因此 jQuery 将无法识别此格式,并将其解释为 Javascript 端的 XML 文档。 您想要的正确 MIME 类型是“文本/纯文本”。

尝试

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

那么您应该收到“videoid”而不是 XML 文档。

您还应该在 jQuery 提示您收到“文本”而不是回复中的任何其他内容:

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

暂无
暂无

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

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