getJSON 和 servlet 通信错误
getJSON and servlet communication error
我让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
更改为get
或ajax
,我会收到以下警报:
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)
相关文章:
- Node.js v6.2.0类扩展不是函数错误
- Jquery菜单操作不稳定,定位不正确,存在一般错误
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- 试图在引导模式内动态生成图表,得到offsetWidth错误
- 为什么会出现错误;未捕获的类型错误:undefined不是函数;
- 我如何修复包含在captcha的addthis中的错误
- 同样,同样的错误'ahorcado.js:26未捕获类型错误:无法读取属性'beginPath'
- 节点是否需要模块传递带有方括号的arg?这是个错误吗
- Webpack/Rect:遵循egghead.io教程,但出现错误:您可能需要一个合适的加载程序来处理此文件类型
- CKFinder 3为所选文件返回错误的URL
- 同位素库错误:未捕获错误无布局模式包装生产线8
- 铬:“;未捕获的语法错误:意外的标记:"
- 如何通过自己获得Chrome扩展的用户反馈/错误报告
- 相位器状态未捕获参考错误
- getJSON 和 servlet 通信错误
- 如何知道在谷歌chrome扩展通信错误
- Angular中指令对指令通信抛出错误
- AngularJS指令与指令之间的通信抛出控制器未找到的错误
- Android WebView Javascript通信错误
- WinForm:与WinForm通信的Javascript错误