我希望用户能够在那里的计算机上选择一个 JSON 文件,然后这个 JSON 文件应该可供客户端 Javascript 使用。
我将如何使用 FILE API 执行此操作,最终目标是用户选择 JSON 文件作为对象可用,然后我可以在 Javascript 中使用它。这是我到目前为止所拥有的:
JsonObj = null
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
f = files[0];
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
JsonObj = e.target.result
console.log(JsonObj);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
小提琴:http : //jsfiddle.net/jamiefearon/8kUYj/
我如何将变量 JsonObj 转换为适当的 Json 对象,可以添加新字段等。