从一个JSP返回JSON到另一个JSP? [英] Return JSON from one JSP to another?

查看:151
本文介绍了从一个JSP返回JSON到另一个JSP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个JSP中是否可以对另一个JSP进行jQuery ajax回调并返回数据?

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

我试图在Page1.jsp的$(document).ready调用中对Page2.jsp进行ajax调用 我正在尝试获取"Page2.jsp"返回的JSON

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"

我正在本地运行Tomcat进行测试. 我看到JSON打印到控制台,但没有返回到Page1.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

有什么想法吗?

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

推荐答案

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

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("\r\n"); I suspect that these character are causing the syntax error.

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

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.

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

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

这篇关于从一个JSP返回JSON到另一个JSP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆