0

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();
%>
4

1 回答 1

1

我尝试了您问题中的代码,jQuery.parseJSON() 代码引发以下错误:“SyntaxError:JSON.parse:意外字符”。调试时看到tomcat生成的servlet代码包含out.write("\r\n"); 我怀疑这些字符导致语法错误。

尽管如此,在 javascript 中,我尝试使用点符号访问返回的对象而不对其进行解析,并且我能够将其视为 JSON 对象。似乎没有必要解析返回的对象。

我对 JSP 代码所做的唯一修改是删除行 PrintWriter out = response.getWriter(); 和 out.close();

于 2013-05-25T17:05:00.180 回答