ClarkeyBoy
ClarkeyBoy

Reputation: 5010

jQuery getJSON - reference pre-existing object

I am using jQuery.getJSON to get some data. I have an object called helpdesk.data.STATUS.MESSAGE.NOTLOGGEDIN which is created in a normal script tag. In the JSON returned by the call to getJSON, I am trying to reference helpdesk.data.STATUS.MESSAGE.NOTLOGGEDIN. I am using the .done method to capture the JSON and do something with it, and .error to catch any errors.

The JSON being returned looks perfectly valid, however it is going into the .error function with a status of 200 (OK).

If I change the reference to the object to a string, it goes into the .done method. Does anyone know of a way to reference an object which already exists within the page firing the getJSON request from the JSON being returned?

The returned JSON is:

{"builds": {"status": helpdesk.data.STATUS.FAILURE, "messages": [helpdesk.data.STATUS.MESSAGE.NOTLOGGEDIN]},"details": {"status": helpdesk.data.STATUS.FAILURE, "messages": [helpdesk.data.STATUS.MESSAGE.NOTLOGGEDIN]}}


Final code:

$.ajax("/helpdesk/resources/js/json/data.json.php", {"data": {"data": "styling-builds,details", "update": "update", "nojson": "nojson"}}).done(function(data) {
    eval("data = " + data);
});

Upvotes: 0

Views: 165

Answers (1)

sdabet
sdabet

Reputation: 18670

To sum it up: it is obviously incorrect to put references to client variables in your JSON response and it will result in invalid JSON format (cf http://json.parser.online.fr/).

The only workaround I see (if you really want to reference an existing variable in your JSON) is to return your response as a string and call eval on it on client-side (variables and functions will be correctly interpreted then).

Upvotes: 1

Related Questions