JSON对象,未定义?

Sho*_*hoe 2 javascript ajax jquery json

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

console.log(response.s);
if (response.s == true) {
    alert('good');
} else {
    alert('bad');
}
Run Code Online (Sandbox Code Playgroud)

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

{"s":true}
Run Code Online (Sandbox Code Playgroud)

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

Cla*_*diu 7

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

  • 是的,这是一个字符串.我刚刚将`dataType:'json'`添加到我的ajax jQuery请求中,它运行正常.谢谢. (3认同)