簡體   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