Newbie
Newbie

Reputation: 361

display json data using xhrget (DOJO)

I am unable to figure out what is the problem with displaying json data..below is the code

var xhrGet1 = dojo.xhrGet({
       url: "Page/",
       handleAs: "json",
       handle: function(response)
       {
       dojo.byId('json-data').innerHTML = response.questions[0];
       }
       });

Html

<div id='json-data'></div>

And my json file looks like this

 {
        "Info": {
            "PURPOSE": "....  ",
            },
        "questions": [
            {
                "ID": 1,
                "Question": "User ID",
                "Information": "",

            }, {
                "ID": 2,
                "Question": "Name",
                "Information": "",

            }
        ],

so on...any ideas??

Upvotes: 1

Views: 2036

Answers (2)

Philippe
Philippe

Reputation: 6828

The property handleAs : "json" in your xhr call makes the incoming json automatically eval'ed to javascript objects. So, you have to convert your javascript object back to string using JSON.stringify. e.g. :

dojo.byId('json-data').innerHTML = JSON.stringify(response.questions[0]);

You can also use dojo.toJson for the same purpose. It uses json.stringify but has the benefit of having a second argument ("prettyprint"), allowing you to pretty-print out of the box, like this :

dojo.byId('json-data').innerHTML = dojo.toJson(response.questions[0], true);

Upvotes: 3

Vijay Agrawal
Vijay Agrawal

Reputation: 3821

wrap your JSON with PRE and CODE tags.

So:

dojo.byId('json-data').innerHTML = "<pre>code>" + response.questions[0] + "</code></pre>";

Also see: Display JSON as HTML for some libraries that can help you pretty-format your JSON when rendering in the browser

Upvotes: 0

Related Questions