stianlp
stianlp

Reputation: 1019

I dont get any data from the getJSON function

I am trying to get a JSON object from a .jsp page. But I dont know what to do with it. I've googeled this for some time now, but I can't find out what this getJSON functions does.

Does it return a string representation of a JSON object?

Or is the parameter 'json' that is passed into the function the JSON Object?

Is the function (the second parameter) equivalent to the function that one write when using XMLHttpRequests? In other words; is this function the asynchronous part?

The alert with "JSON stuff" doesnt print.

<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
    function checkUni() {

        var URL = "http://localhost:8080/GradSchoolApp/test.jsp";

        var jso = $.getJSON(URL, function(json) {
            alert("JSON stuff " + json.name);
        });

        alert(jso);
        //alert(jso.name);

    }

Upvotes: 0

Views: 241

Answers (3)

Shyju
Shyju

Reputation: 218842

Does it return a string representation of a JSON object?

The respone will come as JSON format. getJSON method is a short form of jQuery ajax with datatype as json . The datatype decides what is the format to receive the result from the ajax call.

is the parameter 'json' that is passed into the function the JSON Object?

The variable json in your callback function will get the response from your ajax call. The data should in a valid JSON Document( if your server pages returns like that properly)

is this function the asynchronous part?

As i told you earlier, getJSON is a shortform of jquery ajax with datatype as Json. It is asynchronous.

Upvotes: 2

Charles Bandes
Charles Bandes

Reputation: 795

A few things to check:

Is the webapp also running at localhost:8080? If not, you might be running afoul of the same origin policy, in which case you would need to encode to jsonp.

You should also check in firebug/inspect element/whatever to make sure you are actually getting something returned from your request. You can do this in the network or resources tab depending on which browser you are using. Also stick a breakpoint in your script before the alert and inspect the json object to see if anything was returned.

The second alert isn't firing because the json object doesn't exist yet when you call it.

Upvotes: 3

mgibsonbr
mgibsonbr

Reputation: 22007

The relevant docs for getJSON is here. The callback parameter (that you named json) is the already decoded data (i.e. it's a JavaScript object, not a string).

As for why your alert isn't doing anything, see Charles Bandes's answer. To better debug your code you can also use console.log (will work on Firebug or on Chrome), and/or set a handler to ajaxError - so if the problem is with your request you can be notified of the error (instead of the browser ignoring it by default).

Upvotes: 2

Related Questions