Return JSON from one JSP to another?

Is it possible in one JSP to make a jQuery ajax callback to another JSP and have data returned?

I am trying to make the ajax call to Page2.jsp in the $(document).ready call in Page1.jsp I am attempting to get JSON returned by "Page2.jsp"

I am running Tomcat locally to test. I am seeing the JSON printed to the console, but not returned to the original calling method in Page1.jsp

Any ideas?

Page1.jsp

$(document).ready(function(){

    $.ajax({
        url : 'Page2.jsp',
        dataType: 'json',
        success : function(json) 
        {
            var obj = jQuery.parseJSON(json);
        }
    });
    });

Page2.jsp

<%@page contentType="application/json; charset=UTF-8"%>
<%@page import="org.json.simple.JSONObject"%>
<%

    JSONObject json = new JSONObject();

            json.put("amount","55.00");
            json.put("tax","1.00");

            String jString = JSONObject.toJSONString(json);
            PrintWriter out = response.getWriter();
        out.println(jString);
    out.close();
%>

I tried the code in your question and the jQuery.parseJSON() code throw the following error: "SyntaxError: JSON.parse: unexpected character". On debugging I saw that the servlet code generated by tomcat includes out.write("rn"); I suspect that these character are causing the syntax error.

Nevertheless in the javascript I tried accessing the returned object using the dot notation without parsing it and I was able to so as if it were a JSON object. It appears that it is not necessary to parse the returned object.

The only modification I made to the JSP code was to remove the lines PrintWriter out = response.getWriter(); and out.close();

链接地址: http://www.djcxy.com/p/46072.html

上一篇: 如何使用URLConnection发送对象?

下一篇: 将JSON从一个JSP返回到另一个?