我得到了一些使用“requirejs”的建议,但我无法让它发挥作用。我是 CoffeeScript 的新手,也是 JavaScript 的新手。
我的 JSON 文件(或更准确地说是包含 JSON 字符串的 js 文件)如下所示:
define(function(require)
{
return
{
"name": "Joe",
"age": 30
}
});
我的 app.coffee 有:
requirejs.config
paths:
text: "<path to requirejs-text>"
json_path: "<path to json file>"
我的 main.coffee 有:
define(require) ->
ko = require 'knockout'
$ = require 'jquery'
jsonObj = require 'json_path'
class Main_App
constructor ->
@age = ko.observable jsonObj.age
我在生成的 JavaScript 中遇到以下错误:
Uncaught SyntaxError: Unexpected token :
它提示行中的冒号:
"name": "Joe",
很明显,我的 JSON 字符串周围的 javascript 包装器结构不正确。我想直接读取一个“data.json”文件,但它正在寻找一个“.js”文件。我被告知我需要将 JSON 字符串包装在 javascript“define(function(require)”中,但我似乎无法找到有关如何格式化它的帮助。任何人都能让我摆脱困境? 谢谢!
最佳答案
JavaScript 的自动分号插入似乎在这里是有问题的。
当你写作时
define(function(require)
{
return // a ; is added here.
{
"name": "Joe",
"age": 30
}
});
在 return 语句后面添加了一个分号,因此该函数返回 undefined 而不是您的对象。
试试这样:
define(function(require)
{
return {
"name": "Joe",
"age": 30
};
});
关于javascript - 如何使用 CoffeeScript 加载和使用静态 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24318011/