jQuery 从 servlet 返回 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9645647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return JSON from servlet
提问by user200340
It is a very basic request-response test. Browser sends "hello from browser" to servlet using jQuery $.ajax API, and servlet receives this message, then create a JSON object using org.json.simple library and sends back to browser a JSON response with message "hello from server".
这是一个非常基本的请求-响应测试。浏览器使用 jQuery $.ajax API 向 servlet 发送“hello from browser”,servlet 接收此消息,然后使用 org.json.simple 库创建一个 JSON 对象,并将带有消息“hello from server”的 JSON 响应发送回浏览器。
I am running this on localhost and just assume my IP address is 123.123.12.123, the platform is Ubuntu, server is Tomcat 6.0, running in the Eclipse IDE.
我在本地主机上运行它,假设我的 IP 地址是 123.123.12.123,平台是 Ubuntu,服务器是 Tomcat 6.0,在 Eclipse IDE 中运行。
Test 1. I start the server from Eclipse, open Firefox, enter http://localhost:8080/myproject/test.jsp, I can see servlet receives message and browser receives response, test passed.
测试1.我从Eclipse启动服务器,打开Firefox,输入http://localhost:8080/myproject/test.jsp,可以看到servlet收到消息,浏览器收到响应,测试通过。
Test 2. server is still running at the Eclipse at Ubuntu, I start Windows 7 guest machine from VirtualBox and the Firefox browser in the Windows 7, enter http://123.123.12.123:8080/myproject/test.jsp, works as I expected, test passed.
测试2.服务器仍然在Ubuntu的Eclipse上运行,我从VirtualBox和Windows 7中的Firefox浏览器启动Windows 7客户机,输入http://123.123.12.123:8080/myproject/test.jsp,像我一样工作预期,测试通过。
Test 3. server is still running at Eclipse at Ubuntu, open Internet Explorer 9 browser, give it address http://123.123.12.123:8080/myproject/test.jsp, nothing happens.The debug gives me
测试 3. 服务器在 Ubuntu 的 Eclipse 上仍然运行,打开 Internet Explorer 9 浏览器,给它地址http://123.123.12.123:8080/myproject/test.jsp,没有任何反应。调试给了我
Response HTTP/1.1 200 OK
响应 HTTP/1.1 200 OK
Response body {"message":"hello from server"}
响应正文 {"message":"hello from server"}
The test.jsp is
test.jsp 是
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" type="text/javascript"></script> <script type="text/javascript" src="release/js/libs/json2.js"></script> <script> $(document).ready(function(){ var request = ({"message":'Hello from browser'}); var jsonobj=JSON.stringify(request); $.ajax({ data: {para:jsonobj}, dataType: 'json', url: './TestServlet', type: 'POST', success: function(jsonObj){ alert(jsonObj.message); }, error: function() { alert('Ajax readyState: '+xhr.readyState+'\nstatus: '+xhr.status + ' ' + err); } }); }); </script> <body> </body> </html>
The servlet code is
servlet代码是
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.simple.JSONObject; import org.json.simple.JSONValue; /** * Servlet implementation class TestServlet */ public class TestServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public TestServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf8"); response.setCharacterEncoding("utf8"); response.setContentType("application/json"); PrintWriter out = response.getWriter(); JSONObject jsonObj = (JSONObject) JSONValue.parse(request.getParameter("para")); System.out.println(jsonObj.get("message")); JSONObject obj = new JSONObject(); obj.put("message", "hello from server"); out.print(obj); } }
Update:
更新:
After a closer look by change
仔细观察变化后
error: function() { alert('Ajax readyState: '+xhr.readyState+'\nstatus: '+xhr.status + ' ' + err); }
to
到
error: function(xhr,err) { alert('Ajax readyState: '+xhr.readyState+'\nstatus: '+xhr.status + ' ' + err); }
I got alert readyState:0 and status:0. But I can see {"message":"hello from server"} at Response body and the response header is
我收到了警报 readyState:0 和 status:0。但是我可以在响应正文中看到 {"message":"hello from server"} 并且响应标头是
Key Value Response HTTP/1.1 200 OK
采纳答案by viyancs
IE caches AJAX requests aggressively (more than Firefox, Chrome, and Safari, anyway).
Sometimes you need to set cache header controller when request. Like cache:false
. I tried to fix your code like this
IE 会主动缓存 AJAX 请求(无论如何都比 Firefox、Chrome 和 Safari 多)。有时您需要在请求时设置缓存头控制器。喜欢cache:false
。我试图像这样修复你的代码
request.setCharacterEncoding("utf8");
//response.setCharacterEncoding("utf8");
response.setContentType("application/json");
PrintWriter out = response.getWriter();
JSONObject jsonObj = (JSONObject) JSONValue.parse(request.getParameter("para"));
System.out.println(jsonObj.get("message"));
JSONObject obj = new JSONObject();
obj.put("message", "hello from server");
out.print(obj.toString());
I changed your response content-type from application/json; charset=utf8
to just application/json
and that worked.
我将您的响应内容类型从 更改application/json; charset=utf8
为 justapplication/json
并且有效。
回答by user2190382
I was having the same problem. It was working well on Firefox but not on IE... I found out reading this post that my problem was related to the 'Content-Type'. The problem seems that that IE has problem with 'charset=UTF8'. However, if you use 'charset=UTF-8' (with a dash) it is then working! Your Content-Type should then be: application/json;charset=UTF-8
我遇到了同样的问题。它在 Firefox 上运行良好,但在 IE 上运行良好......我发现阅读这篇文章时我的问题与“内容类型”有关。问题似乎是 IE 对 'charset=UTF8' 有问题。但是,如果您使用 'charset=UTF-8'(带破折号),那么它就可以工作了!你的内容类型应该是:application/json;charset=UTF-8
回答by phuongmychi
<%
Gson gs = new Gson();
BeanHelpBH bh = new BeanHelpBH();
List<Baihatmoi> lst = bh.getTenbaihatbyName("Ao moi ca mau");
String bha = gs.toJson(lst);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(bha);
out.flush();
%>
script :
<script>
$(document).ready(function(){
$.get('jsontest.jsp',function(data){
[enter image description here][1] console.log(data);
});
});
</script>
回答by xrcwrn
using Gson you can send json response
使用 Gson 你可以发送 json 响应
@WebServlet(urlPatterns = {"/jsonResponse"})
public class JsonResponse extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Student student = new Student(12, "Ram Kumar", "Male", "1234565678");
Subject subject1 = new Subject(1, "Computer Fundamentals");
Subject subject2 = new Subject(2, "Computer Graphics");
Subject subject3 = new Subject(3, "Data Structures");
Set subjects = new HashSet();
subjects.add(subject1);
subjects.add(subject2);
subjects.add(subject3);
student.setSubjects(subjects);
Address address = new Address(1, "Street 23 NN West ", "Bhilai", "Chhattisgarh", "India");
student.setAddress(address);
Gson gson = new Gson();
String jsonData = gson.toJson(student);
PrintWriter out = response.getWriter();
try {
out.println(jsonData);
} finally {
out.close();
}
}
}
}
for more json response from servlet in java