将外部JSON分配给var

时间:2011-06-15 19:44:49

标签: javascript json dojo assign

我使用JSON中的值填充Dojo Combobox下拉列表。 下面的代码工作正常(内联JSON).....

<script>
var magicvars = {
   identifier: 'name',
   label: 'name',
   items: [
   {name: "ZCCN_NO_1", label: "<img width='16px' height='16px' src='http://localhost:3000/static/images/eight_ball_16x16.png'/>ACCN_NO_1"},
   {name: "CR_Local_ID", label:"<img width='16px' height='16px' src='http://localhost:3000/static/images/eight_ball_16x16.png'/>CR_Local_ID"}
]};
</script>

<div dojoType="dojo.data.ItemFileReadStore" data="magicvars" jsId="xvarStore2"></div>

但是,当我为JSON指定外部文件时,没有go,也就是说下拉列表会填充。 外部文件是standard.txt,看起来像这样......

{
  identifier: 'name',
  label: 'name',
  items: [
  {name: "ZCCN_NO_1", label: "<img width='16px' height='16px' src='http://localhost:3000/static/images/eight_ball_16x16.png'/>ACCN_NO_1"},
  {name: "CR_Local_ID", label:"<img width='16px' height='16px' src='http://localhost:3000/static/images/eight_ball_16x16.png'/>CR_Local_ID"}
 ]};

我对dojo的HTML调用看起来像这样..

<div dojoType="dojo.data.ItemFileReadStore" jsId="xvarStore2" url="http://localhost:3000/static/standard.txt">
</div>

内联工作正常但外部调用没有。如果这是一个补救问题,请道歉,但我如何阅读外部文件并将其分配给“magicvars”。我只是不想用一堆内联JSON来混淆HTML。

任何建议表示赞赏。 珍妮

2 个答案:

答案 0 :(得分:1)

它不是有效的JSON,因此不会解析大多数JSON.parse实现。尝试引用键名并删除尾随分号。

在Chrome上,

JSON.parse('{ a: "b" }')

产生

SyntaxError: Unexpected token ILLEGAL

一样
JSON.parse('{ a: "b" };')

但使用有效的JSON(请注意"a"周围的引号)

JSON.parse('{ "a": "b" }')

返回预期结果。

答案 1 :(得分:0)

尝试将文件重命名为standard.json

我的猜测是,dojo正在将您的文件作为纯文本字符串读取,因此不会解析JSON。 (正如其他答案所指出的那样,有效)