【问题标题】:jQuery with json带有 json 的 jQuery
【发布时间】:2010-03-23 09:43:28
【问题描述】:

我有以下 json 代码文件名为:sections.json

{
    "section1": { "priority": 1, "html": '<img src="../images/google.png" />'},
    "section2": { "priority": 2, "html": '<input type="button" value="Login" />'},
    "section3": { "priority": 3, "html": '<div>Some text</div>'},
    "section4": { "priority": 4, "html": '<div>Some text</div>'},
    "section5": { "priority": 5, "html": '<select><option>option1</option> <option>option2</option></select>'}
}

我正在 jquery 代码中尝试此操作,但警报不起作用

$.getJSON("sections.json", function(json) {
    alert('h');
});

【问题讨论】:

  • 文件的路径是否正确?
  • “不工作”是什么意思?会发生什么?如果您使用 Firebug 检查 DOM 和任何 XHR 请求会怎样?

标签: jquery json


【解决方案1】:

你的 JSON 应该是这样的:

{
  "section1": { "priority": 1, "html": "<img src='../images/google.png' />"},
  "section2": { "priority": 2, "html": "<input type='button' value='Login' />"},
  "section3": { "priority": 3, "html": "<div>Some text</div>"},
  "section4": { "priority": 4, "html": "<div>Some text</div>"},
  "section5": { "priority": 5, "html": "<select><option>option1</option> <option>option2</option></select>"}
}

值必须是 double 引用才能成为有效的 JSON,单引号不会这样做:) 从 jQuery 1.4 开始,默认情况下不再允许无效的 JSON(他们添加了一些额外的检查以确保它是有效的,并且您问题中的 JSON 被那些阻止了:)

【讨论】:

    【解决方案2】:

    似乎是无效的 JSON,因此 JQuery 静默失败(请参阅 http://api.jquery.com/jQuery.getJSON/)。尝试http://www.jsonlint.com/ 验证您的 JSON 文件。

    例如对于第 1 节,html 的值应为 "&lt;img src='../images/google.png' /&gt;"

    查看此答案以获取 JSON 中的 html 标记示例:HTML tags within JSON (in Python)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多