简体   繁体   English

Java / Javascript / JSON-将JSON字符串从Java传递到Javascript

[英]Java/Javascript/JSON - Passing JSON string from Java into Javascript

I'm passing a JSON string I create in Java as a parameter to a Javascript method called from my servlet. 我将在Java中创建的JSON字符串作为参数传递给从Servlet调用的Javascript方法。 However, when I pass the JSON string, Firebug warns me about the string being passed: 但是,当我传递JSON字符串时,Firebug会警告我有关正在传递的字符串的信息:

Java code: Java代码:

String jsonString = "{\"id\":1,\"name\":\"Joe Smith\",\"data\":{\"email\":\"smith@gmail.com\",\"phone\":\"555-123-4567\",\"title\":\"CFO\",\"instanceControllerTagLibraryApi\":{\"developmentMode\":false}},\"children\":[],\"instanceControllerTagLibraryApi\":{\"developmentMode\":false}}";

pw.println("<body onload=\"init('"+jsonString+"');\">");

Javascript: Javascript:

function init(text){
    alert(text);
}

I've tried quoting the string during the pass and removing the single quotes. 我试过在传递过程中引用字符串并删除单引号。 Both basically point to the fact that the string being passed needs to escape the curly braces (somehow). 两者基本上都指向一个事实,即所传递的字符串需要转义花括号(以某种方式)。

Error (single quote): 错误(单引号):

SyntaxError: unterminated string literal [Break On This Error] SyntaxError:无终止的字符串文字[此错误中断]

init('{ 在里面('{

The error is not in the JSON string, it's in the other bit of code. 错误不在JSON字符串中,而是在另一部分代码中。

pw.println("<body onload=\\"init('"+jsonString+"');\\">"); is really crude attempt to add an onload event. 尝试添加onload事件真的是很粗糙的尝试。

Don't try to add the JSON string into the HTML string, it wont work because of the quotes, unless you doubly escape the JSON string, which is just silly. 不要尝试将JSON字符串添加到HTML字符串中,因为引号将无法正常工作,除非您将JSON字符串加倍转义,这很愚蠢。

Currently you output will look like: 当前,您的输出将如下所示:

<body onload="init('{"id":1, ... }');">
                     ^--- syntax error after this

It will try to execute the JS code init('{ . 它将尝试执行JS代码init('{

Frits was able to figure out your problem, which was good. Frits能够找出您的问题,这很好。 I would definitely take his advice and move away quickly from using body onload . 绝对会听取他的建议,并迅速摆脱body onload

For instance: 例如:

(function run(){
    var data = '{"id":1,"name":"Joe Smith","data":{"email":"smith@gmail.com","phone":"555-123-4567","title":"CFO","instanceControllerTagLibraryApi":{"developmentMode":false}},"children":[],"instanceControllerTagLibraryApi":{"developmentMode":false}}';

    function init(){
        console.log(data, JSON.parse(data));
    }

    if (window.addEventListener) {
        window.addEventListener('load', init);
    } else if (window.attachEvent) {
        window.attachEvent('load', init);
    }
​})();​

http://jsfiddle.net/userdude/eQRBk/1/ http://jsfiddle.net/userdude/eQRBk/1/

Notice the use of window.addEventListener (and the legacy window.attachEvent for older IE versions). 请注意window.addEventListener的使用(对于较旧的IE版本,则使用传统的window.attachEvent )。 And that console.log works better in Chrome and Firebug; 而且console.log在Chrome和Firebug中效果更好。 IE's console is a little more frustrating in how it logs objects, in my opinion. 我认为,IE的控制台在记录对象的方式上更加令人沮丧。

Using what you've given, you could (and I would suggest should) handle it differently. 使用给出的内容,您可以(我建议应该)以不同的方式处理它。 Forgive me, however, I'm not that well-versed in Java and JSP is all I know (barely). 但是,请原谅我,我对Java并不了解,而JSP只是我所了解的(很少)。 So...? 所以...?

<%

String jsonString = "'{\"id\":1,\"name\":\"Joe Smith\",\"data\":{\"email\":\"smith@gmail.com\",\"phone\":\"555-123-4567\",\"title\":\"CFO\",\"instanceControllerTagLibraryApi\":{\"developmentMode\":false}},\"children\":[],\"instanceControllerTagLibraryApi\":{\"developmentMode\":false}}'";

%>
<script>
(function run(){
    var data = <%=jsonString%>;

    function init(){
        console.log(data, JSON.parse(data));
    }

    if (window.addEventListener) {
        window.addEventListener('load', init);
    } else if (window.attachEvent) {
        window.attachEvent('load', init);
    }
​})();​
</script>

And then you can insert that JSP page into the head or the body and it will work fine. 然后,您可以将该JSP页面插入headbody ,它将正常工作。 I also imagine you could set it up to dynamically inject that data into the JSP page. 我也想像您可以将其设置为动态地将数据注入JSP页面。 But, like I said, I'm kinda waving my hands here. 但是,就像我说的,我有点在这里挥舞着双手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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