Javascript JSON 对象,未定义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5353874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:48:56  来源:igfitidea点击:

JSON Object, undefined?

javascriptjqueryajaxjson

提问by Shoe

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

我正在尝试使用 jQuery、AJAX 和 JSON 开发 Web 应用程序。我有这个代码:

console.log(response.s);
if (response.s == true) {
    alert('good');
} else {
    alert('bad');
}

This response(via console.log()on Firebug) seems to be:

response(通过console.log()Firebug)似乎是:

{"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?

这似乎是一个 JSON 对象,对吗?好吧,console.log(response.s);我在此处添加的第一个代码行返回undefined. 有什么问题?

回答by Claudiu

What is typeof (response)? if it's a string then you have to parse it, first. (You'd be accessing the sfield of a string, which doesn't exist, so JavaScript gives you undefinedinstead of throwing an Exception or whatever.)

什么是typeof (response)?如果它是一个字符串,那么你必须首先解析它。(您将访问s一个不存在的字符串字段,因此 JavaScript 会为您提供undefined而不是抛出异常或其他任何内容。)

回答by Coin_op

If the content-typeof the response isn't application/jsonthen the javascript is probably assuming that it is just a string.

如果content-type响应的 不是application/json那么 javascript 可能假设它只是一个字符串。

Supplying the correct content header should therefore sort your problem.

因此,提供正确的内容标题应该可以对您的问题进行排序。

Alternatively you could probably use eval()to convert the string into a json object.

或者,您可能会使用eval()将字符串转换为 json 对象。

回答by alexl

try to use:

尝试使用:

var obj = jQuery.parseJSON(response);
console.log(obj.s);

Hope it helps.

希望能帮助到你。