开发者

passing json from servlet to dojo

开发者 https://www.devze.com 2022-12-25 17:50 出处:网络
I am currently trying to pass a generated JSON string to dojo for parsing and am having some issues. The servlet simply writes it as a string as so:

I am currently trying to pass a generated JSON string to dojo for parsing and am having some issues. The servlet simply writes it as a string as so:

response.getWriter().append("{ \"data\": {开发者_Go百科");
response.getWriter().append("\"type\": \"facing\",");
response.getWriter().append("\"score\": " + "\"" + score + "\",");
response.getWriter().append("\"count\":" + "\"" + count + "\"" );
response.getWriter().append("}}");

which prints as:

{"data":{"type":"facing","score":"10","count":"24"}}

And the parsing on the dojo end looks as so:

dojo.xhrPost({
    url: url,
    handleAs: "json",
    load: function(data) {
        alert(data);
        /* Parse Not working */
        alert(data.data[0].type);  
    },
    error: function(error) {
        alert("No dice")
    }
});

The main issue is the data.data[0].type is returning nothing but when i print this out as text the json seems to be correctly formatted. Any help with this would be appreciated.


Self-Solved: Only use the [] operator to dereference values from arrays but if extracting values from object use the dot notation. So to get the type one would simply need to do: data.data.type


I strongly recommend using Google Gson to convert maps and/or collections of fullworthy javabeans to JSON and vice versa. You can find here several examples. Learning JSON would also help much.

0

精彩评论

暂无评论...
验证码 换一张
取 消