1

I'm currently creating an ArrayList in Java, then running the .toJson function from Google-gson on it:

public String statusesToJson(ArrayList<String> statuses){
    Gson gson = new Gson();
    return gson.toJson(statuses);
}

Which results in the JSON:

[ "u", "u", "u", "u" ]

Then in JSP I'm passing it into JavaScript:

<script language="JavaScript" type="text/javascript">CheckStatus.loaded('<%=model.getPageId() %>', '<%=request.getContextPath() %>', '<%=model.arrayListToJson(model.getStatuses()) %>');</script>

Then in the JavaScript I'm parsing it to a JSON array:

CheckStatus.statuses = JSON.parse(statuses);
alert(CheckStatus.statuses);

This then results in the following output:

u, u, u, u

The problem is that the following doesn't work and causes my page to not load:

alert(CheckStatus.statuses[0]);

What's wrong with this?

EDIT: Loaded Function:

loaded : function(guid, context, statuses) {
        CheckStatus.guid = guid;
        CheckStatus.context = context;
        CheckStatus.statuses = JSON.parse(statuses);
        alert(CheckStatus.statuses[0]);

        if(CheckStatus.init == null){
            submitForm('checkStatusForm', CheckStatus.guid);
            CheckStatus.init = true;
        }

        setupForm('checkStatusForm', function(){CheckStatus.validStatus();});

        //CheckStatus.setImages();

        applyCSS3('Check_Status');
    }

Valid Status Function:

validStatus : function(){
        CheckStatus.params = $('#checkStatusForm').serializeObject();

        if(document.getElementById('regionID').value != "" && document.getElementById('regionAction').value != ""){
            submitForm('checkStatusForm', CheckStatus.guid);
        }else{
            error("Cannot Commit", "You must select an action before attempting to commit.");
        }
    },

Setup Form Function:

/**
 * Sets up the form to submit when the user presses enter inside an input
 * element. Also calls the callback when the form is submitted, does not
 * actually submit the form.
 * 
 * @param id The id of the form.
 * @param callback The callback to call.
 * @return Nothing.
 */
function setupForm(id, callback) {
    $('#' + id + ' input').keydown(function(e) {
        if (e.keyCode === 13) {
            $(this).parents('form').submit();
            e.preventDefault();
        }
    });
    $('#' + id).submit(function(e) {
        e.preventDefault();
        callback();
    });
}

Submit Form Function:

/**
 * Serializes and submits a form.
 * 
 * @param id
 *            The id of the form to submit.
 * @param guid
 *            The guid of the page the form is on to pass to the server.
 * @return nothing.
 */
function submitForm(id, guid) {
    var subTabId = $('#' + id).closest('#tabs > div > div').attr(
            'id'), tabId = $('#' + id).closest('#tabs > div')
            .attr('id'), data = $('#' + id).serializeArray();
    data.push( {
        name : "framework-guid",
        value : guid
    });
    $.ajax( {
        type : 'POST',
        cache : 'false',
        url : '/pasdash-web/' + tr("_", "", tabId.toLowerCase()) + '/' + tr("_", "", subTabId)
                + '.jsp',
        data : data,
        success : function(html) {
            $('#' + subTabId).html(html);
            resourceChanged(tabId, subTabId,
                    $('#' + id + ' input[name="framework_command"]')[0].value,
                    guid);
        },
        error : function(jqXHR, textStatus, errorThrown) {
            error('Ajax Error', textStatus);
        }
    });
    return false;
}
8
  • 3
    "I'm parsing it to a JSON array" -> No you're not, you're parsing it from a JSON array to a JavaScript Array. Commented Jun 5, 2012 at 20:47
  • What exactly does that "loaded" function do? There's very likely no reason at all for you to have to express the JSON as a string; it's redundant. Commented Jun 5, 2012 at 20:47
  • Hmmm....isn't JSON supposed to be name:value pairs? That just looks like a regular old JS array. Commented Jun 5, 2012 at 20:48
  • 2
    @Diodeus — No, the outer most data structure in a JSON text can be an object or an array. Commented Jun 5, 2012 at 20:48
  • 1
    Could you give use the HTML output of that script element, instead of the jsp code? Commented Jun 5, 2012 at 20:51

3 Answers 3

1

You don't need to wrap your JSON with strings, that will just force you to have to reparse it. I would try removing those quotes and not calling JSON.parse

loaded : function(guid, context, statuses) {
    CheckStatus.guid = guid;
    CheckStatus.context = context;
    // Here's the change
    CheckStatus.statuses = statuses;
    alert(CheckStatus.statuses[0]);

And change your HTML to be

<script type="text/javascript">
    CheckStatus.loaded('<%=model.getPageId() %>', 
                       '<%=request.getContextPath() %>',
                       // the following line should output something like
                       // ["a", "b"]
                       // which is perfectly valid JavaScript
                       <%=model.arrayListToJson(model.getStatuses()) %>);
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

I think I already tried that once and the page still froze. I'll try it again when I get back to work in the morning and see what sort of console output it gives if it doesn't work.
Alright, so initially that didn't work, as I recalled from the first time I tried it. However, now that I knew about the browser console I examined that output and saw that the array was null on the initial page load. I just threw in an if statement to see if it was null before doing anything with it and it worked perfectly!
0

You should be able to write:

CheckStatus.loaded('<%=model.getPageId() %>', '<%=request.getContextPath() %>', <%=model.arrayListToJson(model.getStatuses()) %>);

without the quotes around the last argument. Then, that "loaded()" function will get the object directly and there'll be no need to call "JSON.parse()".

14 Comments

Also it makes me really sad to see scriptlets in JSP in 2012.
Removing the quotes and the JSON.parse(), then calling alert(CheckStatus.statuses[0]); still causes the page not to load.
try removing the quotes but keeping the parse
Well you're not giving us a lot to work with here, @PseudoPsyche. That "loaded" function that's called: what exactly does it do?
It handles the form submissions somehow: loaded : function(guid, context, statuses) { CheckStatus.guid = guid; CheckStatus.context = context; CheckStatus.statuses = JSON.parse(statuses); alert(CheckStatus.statuses[0]); if(CheckStatus.init == null){ submitForm('checkStatusForm', CheckStatus.guid); CheckStatus.init = true; } setupForm('checkStatusForm', function(){CheckStatus.validStatus();}); //CheckStatus.setImages(); applyCSS3('Check_Status'); }
|
0

Check the type of the result of JSON.parse (). Seems to me that it is a string and not an array. Maybe a pair of quotes somewhere that should not be there?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.