最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JSON Object, undefined? - Stack Overflow

programmeradmin4浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论