getJSON和servlet通信错误

时间:2012-08-06 14:37:23

标签: javascript servlets

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

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 on this servelet的URL,检索字符串:

"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上运行

感谢所有帮助

4 个答案:

答案 0 :(得分:2)

尝试这样的事情:

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

答案 1 :(得分:0)

输出:

"Hello World from servlet!"

这是一个字符串,而不是JSON对象,通过jsonlint.com运行它。您的输出应该类似于:

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

使用适当的内容类型“application / json”设置。

如果您只想获得纯文本字符串,请使用$.get()

答案 2 :(得分:0)

写是这样的,

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

关于JS,

alert(data.message);

答案 3 :(得分:0)

另外,我在Chrome下的javascript控制台说:

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)