简体   繁体   中英

Java servlet not returning JSON Object to jquery ajax

i am building web using JSP with servlet. I code JSP to get data from Servlet using jquery ajax, which is returning JSON type. but when i tried to convert servlet response data into JSON and try to logging with console.log on ajax success, it's not returning JSON Object.

i'm using org.json.simple.JSONObject library for converting.

Here is my jquery code :

$.ajax({
    url : BASEPATH + 'load',
    type : 'get',
    success : function(response) {
        console.log(response);
    },
    error : function(response) {
        alert('error');
    }
});

Here is my servlet code :

import org.json.simple.JSONObject;

public class SourceSystemServlet extends HttpServlet
{
    JSONObject resp = new JSONObject();

    public SourceSystemServlet()
    {
        super();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        int code = 0;
        String message = "";

        code = 200;
        message = "Success";

        resp.put("code", code);
        resp.put("message", message);
        response.setContentType("application/json");
        response.getWriter().write(resp.toString());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        doPost(req, resp);
    }
}

i want to get data JSON object like this :

在此处输入图片说明

but what i've got is data string like this, so i can't use response as object to logging ie console.log(response.code) :

在此处输入图片说明

i hope someone can help me, thanks.

我认为您可以尝试resp.toJSONString()而不是resp.toString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM