Ricky Mason
Ricky Mason

Reputation: 1828

Converting JSON array to html

I have successfully returned a JSON object/array(not too good with terminology), using the below code.

$(function(){
    $("#buildForm").click(function(e){
        e.preventDefault();
        var frm = $(document.buildForm);
        var dat = JSON.stringify(frm.serializeArray());
        $.post(frm.attr("action"), {data:dat}, function(response) 
        {
            var $dialog = $('<div></div>')
            .html(response)
            .dialog({
                    autoOpen: false,
                    title: 'Build',
                    modal: true,
                    height: 400
            });
            $dialog.dialog('open');

            // prevent the default action, e.g., following a link
            return false;
        });     
});
});

It returns

{"str_id":"1","str_name":"TC","tier_id":"1","buy_gold":"50000","buy_mana":"10000","res_build":"0","res_active":"0","res_owned":"0","timebuildmins":"500","timecollectmins":"30","timeminsformiss":"0","goldcollected":"1000","str_imageloc":"..\/img\/structures\/tc.png"}

I don't know much JS, but im trying to learn by doing. Unfortunately, I can't figure out how to simply display, for instance, only the "str_name."

As you can see, I have a popup window from the jquery ui open to display the retrieved data in JSON format. I need to be able to take bits of the returned data and display it! Simple right? Please help!

Upvotes: 0

Views: 1095

Answers (2)

Morgon
Morgon

Reputation: 3319

If I'm reading your question right, what you had returned was a JSON-formatted string, not an actual object. If that's the case, you'll want to use the JSON.parse() method to turn that into an accessible object:

ret = JSON.parse(response);
// ret.str_name now returns 'TC'

Upvotes: 1

Matt
Matt

Reputation: 75317

You can use response.str_name to access the value of the str_name member. Your code would then look like;

var $dialog = $('<div></div>')
.html(response.str_name)
.dialog({
        autoOpen: false,
        title: 'Build',
        modal: true,
        height: 400
});
$dialog.dialog('open');

What you had before (.html("response")) meant you were setting the HTML to the string "response".

To clear you up on your terminology; what you would have received from the server would be a JSON formatted string (e.g. a string which was valid JSON notation). Traditionally would then parse the JSON string to give you a JavaScript object to manipulate.. however, jQuery intelligently detected the JSON response, and has already parsed it into an object for you; hence what you receive in the response parameter is a standard JavaScript object. If this is still confusing, you might find the following post useful; Javascript object Vs JSON

Upvotes: 2

Related Questions