jquery – 从servlet返回JSON

前端之家收集整理的这篇文章主要介绍了jquery – 从servlet返回JSON前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道这个类型的问题已经被问过了,但我不能得到这个工作.

这是一个非常基本的请求响应测试.浏览器使用JQuery $.ajax API向浏览器发送“hello”到servlet,servlet收到此消息,然后使用org.json.simple库创建一个JSON对象,并向浏览器发送一条消息“hello from server”的JSOn响应.

我在localhost上运行这个,只是假设我的ip地址是123.123.12.123,平台是Ubuntu,服务器是Tomcat 6.0,在Eclipse IDE中运行.

测试1.我从Eclipse启动服务器,打开Firefox,输入http://localhost:8080/myproject/test.jsp,我可以看到servlet接收消息和浏览器收到响应,测试通过.

测试2.服务器仍然在Eclipse的Ubuntu上运行,我从VirtualBox和Windows 7中的Firefox浏览器启动Windows 7客机,输入http://123.123.12.123:8080/myproject/test.jsp,按照我的预期工作,测试通过.

测试3.服务器仍然在Eclipse在Ubuntu上运行,打开Internet Explorer 9浏览器,给它地址http://123.123.12.123:8080/myproject/test.jsp,没有任何反应.
调试给了我

响应HTTP / 1.1 200 OK

响应体{“message”:“来自服务器的hello”}

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>
<@R_404_338@ 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>

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();
        // TODO Auto-generated constructor stub
    }

    /**
     * @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,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);

    }

}

谢谢.

更新:

经过变化仔细观察

 error: function() {
            alert('Ajax readyState: '+xhr.readyState+'\nstatus: '+xhr.status + ' ' + err);
}

error: function(xhr,err) {
            alert('Ajax readyState: '+xhr.readyState+'\nstatus: '+xhr.status + ' ' + err);
        }

我有警告readyState:0和状态:0.
但是我可以在响应机构处看到{“message”:“hello from server”}
响应头是

Key Value
Response    HTTP/1.1 200 OK

解决方法

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

我从应用程序/ json更改了你的响应内容类型charset = utf8只是应用程序/ json并且工作.

猜你在找的jQuery相关文章