getJSON 和 servlet 通信错误

getJSON and servlet communication error

本文关键字:错误 通信 servlet getJSON      更新时间:2023-09-26

我让tomcat在端口8080和简单的servlet上运行:

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.*;
public class MyHelloWorld extends HttpServlet {
    public void doGet(HttpServletRequest request, 
            HttpServletResponse response)
    throws IOException, ServletException
    {
        String data = "Hello World from servlet!";
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(data);
    }
}

wget 在 URL 上指向此 servlet,检索一个字符串:

"Hello World from servlet!"

网络浏览器也会打印它,所以它可以工作,Tomcat的访问日志显示响应"200"

但是当我试图通过我的 javascript 获取这个字符串时:

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>

            $.getJSON({ 
    type: "GET", url: "http://localhost:8080/examples/MyHelloWorld", 
    contentType: "text/plain", 
    error: function(xhr, ajaxOptions, thrownError){ 
                alert(ajaxOptions);
                alert(xhr.status); 
                alert(thrownError);
            }, 
    processData: true, 
    success: function(data, textStatus, jqXHR){ alert(data); }
});
</script>
</script>
</head>

在 tomcat 的日志中,我可以看到响应 200,但浏览器没有显示任何内容 - 只是没有内容的空白页。如果我将getJSON更改为getajax,我会收到以下警报:

xhr.status = 0
ajaxOptions = "error"
thrownError = empty

Web服务器是Apache,它运行在端口80上

感谢所有帮助

尝试这样的事情:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    String data = "Hello World from servlet!";
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    if (request.getContentType().equals("application/json")) {
        data = "'"" + data + "'"";
    }
    response.getWriter().write(data);
}

在你的js中:

$.getJSON("http://localhost:8080/examples/MyHelloWorld", function(data) {
   alert(data)
})

写是这样的,

 String data = "{'"message'":'"Hello World from servlet!'"}";

在JS上做,

alert(data.message);

输出:

"Hello World from servlet!"

这是一个字符串,而不是 JSON 对象,通过 jsonlint.com 运行它。您的输出应如下所示:

{ "data" : "Hello World from servlet!" }

设置了正确的内容类型"应用程序/JSON"。

如果你只想获取一个纯文本字符串,请使用 $.get()。

另外,我在chrome下的java scripit控制台说:

GET http://10.10.1.19/[object%20Object] 404 (Not Found) jquery-latest.min.js:4
f.support.ajax.f.ajaxTransport.send jquery-latest.min.js:4
f.extend.ajax jquery-latest.min.js:4
f.each.f.(anonymous function) jquery-latest.min.js:4
f.extend.getJSON jquery-latest.min.js:4
(anonymous function)