javascript 尝试使用下划线解析 JSON(Chrome 上的意外令牌)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19426222/
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
Trying to parse JSON with underscore (Unexpected token on Chrome)
提问by WhatisSober
Hello I am trying to get a grasp on underscore.js
您好,我正在尝试了解 underscore.js
i have a json file as follows:
我有一个 json 文件如下:
[
{
"name":"rocky",
"last-updated": "Yesterday",
"age":"32"
},
{
"name":"annie",
"last-updated": "Today",
"age":"31"
}
]
And a javascript function:
还有一个 javascript 函数:
function getNames() {
var users = $.ajax({
url : "users.json",
async : false
});
var names = _.map(JSON.parse(users.responseText),
function(user) {
return user.name
});
return names;
}
It works fine on IE but on Chrome, it throws me:
它在 IE 上运行良好,但在 Chrome 上,它抛出了我:
Uncaught SyntaxError: Unexpected token ,
on this line:
在这一行:
var names = _.map(JSON.parse(users.responseText),function(user) {return user.name});
As far as I know this error is because of trying to parse object not the JSON string. Am i right? How do I solve this? It works on IE?
据我所知,这个错误是因为试图解析对象而不是 JSON 字符串。我对吗?我该如何解决这个问题?它适用于 IE 吗?
Thank you!
谢谢!
采纳答案by WhatisSober
It turned out the problem was with urlparameter.
原来问题出在url参数上。
url : "users.json"
url: "/users.json"
Error thrown by Chrome:
Chrome 抛出的错误:
Uncaught SyntaxError: Unexpected token ,
After an hour of troubleshooting, i found out: Chrome has a bug on caching GET requests.
经过一个小时的故障排除后,我发现: Chrome 在缓存 GET 请求方面存在错误。
It can be fixed by setting
可以通过设置修复
cache: false
on my Ajax call!
在我的 Ajax 通话中!
Also making a directory and calling that directory on urlseems to be working.
还创建一个目录并在url上调用该目录似乎正在工作。
url : "json/users.json"
Thanks to those who tried to help.
感谢那些试图提供帮助的人。