javascript - JSON Object, undefined? - Stack Overflow

I'm trying to develop a web application using jQuery, AJAX and JSON.I have this code:console.log(

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?

Share Improve this question asked Mar 18, 2011 at 15:06 ShoeShoe 76.3k38 gold badges176 silver badges278 bronze badges 2
  • 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
Add a ment  | 

3 Answers 3

Reset to default 8

What 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1740230776a4212495.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信