【发布时间】:2014-02-04 08:46:21
【问题描述】:
我正在使用文件阅读器 API:
if (window.File && window.FileReader && window.FileList && window.Blob) {
} else {
alert('The File APIs are not fully supported in this browser.');
return;
}
input = document.id('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
} else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
} else {
file = input.files[0];
fr = new FileReader();
fr.onload = function () {
console.log(JSON.parse(fr.result));
}
fr.readAsText(file);
}
我在控制台中得到了这个:
{"id":"2","name":"Links1","position":"1","author":"Demo","email":"info@demo.com","description":"","html":"<div class=\"units-row-end\" id=\"links\"><\/div>","css":"","js":"var out = '<a href=\"#!index\" class=\"home\">Home<\/a> ';\nout += user.type ? '<a href=\"#!logout\">Logout<\/a> ' : '<a href=\"#!login\">Login<\/a> ';\nout += user.type ==2 ? '<a href=\"#!admin?template=overview\">Account<\/a> ' : user.type == 1 ? '<a href=\"#!user?template=overview\">Account<\/a> ' : '';\nout += user.type !=2 ? '<a href=\"#!cart\">Cart<\/a>' : '';\n\ndocument.id('links').set('html', out);","status":"1"}
此输出不是我控制台中的对象!为什么? 如果我试图将上面的字符串复制到:http://json.parser.online.fr/ 这个字符串将转换为对象。 哪里出了问题?
附言 我的文件内容(fr.result):
"{\"id\":\"2\",\"name\":\"Links1\",\"position\":\"1\",\"author\":\"Demo\",\"email\":\"info@demo.com\",\"description\":\"\",\"html\":\"<div class=\\\"units-row-end\\\" id=\\\"links\\\"><\\\/div>\",\"css\":\"\",\"js\":\"var out = '<a href=\\\"#!index\\\" class=\\\"home\\\">Home<\\\/a> ';\\nout += user.type ? '<a href=\\\"#!logout\\\">Logout<\\\/a> ' : '<a href=\\\"#!login\\\">Login<\\\/a> ';\\nout += user.type ==2 ? '<a href=\\\"#!admin?template=overview\\\">Account<\\\/a> ' : user.type == 1 ? '<a href=\\\"#!useraccount?template=overview\\\">Account<\\\/a> ' : '';\\nout += user.type !=2 ? '<a href=\\\"#!cart\\\">Cart<\\\/a>' : '';\\n\\ndocument.id('links').set('html', out);\",\"status\":\"1\"}"
【问题讨论】:
-
JSON.parse(fr.result)是一个对象。检查它-console.log(typeof JSON.parse(fr.result)) -
控制台显示:字符串
-
我们需要知道
fr.result的外观以及我们正在谈论的控制台(Firefox?Firebug?Chrome?Internet Explorer?)。关于 FileReader API 的其余代码似乎不相关。 -
请检查我上面的 fs.result(文件内容)
标签: javascript css json filereader