I'm trying to develop a web application using jQuery, AJAX and JSON. I have this code:
console.log(response.s);
if (response.s == true) {
alert('good');
} else {
alert('bad');
}
This response
(via console.log()
on Firebug) seems to be:
{"s":true}
Which seems to be a JSON object right?
Well, the line console.log(response.s);
on the first code I added here returns undefined
. What's the problem?
I'm trying to develop a web application using jQuery, AJAX and JSON. I have this code:
console.log(response.s);
if (response.s == true) {
alert('good');
} else {
alert('bad');
}
This response
(via console.log()
on Firebug) seems to be:
{"s":true}
Which seems to be a JSON object right?
Well, the line console.log(response.s);
on the first code I added here returns undefined
. What's the problem?
- Can you click the {"s":true} object within Firebug console and see it in object (DOM) explorer or is it written as string in the Firebug console (i.e. not clickable)? – Nikhil Commented Mar 18, 2011 at 15:09
- @Nikhil, i guess it more like a string. – Shoe Commented Mar 18, 2011 at 15:10
3 Answers
Reset to default 8What is typeof (response)
? if it's a string then you have to parse it, first. (You'd be accessing the s
field of a string, which doesn't exist, so JavaScript gives you undefined
instead of throwing an Exception or whatever.)
If the content-type
of the response isn't application/json
then the javascript is probably assuming that it is just a string.
Supplying the correct content header should therefore sort your problem.
Alternatively you could probably use eval()
to convert the string into a json object.
try to use:
var obj = jQuery.parseJSON(response);
console.log(obj.s);
Hope it helps.