【发布时间】:2015-09-28 09:05:39
【问题描述】:
我正在使用 .json 文件和 jQuery 的 $.getJSON 用文本填充 divs,我的代码如下所示:
代码:
$.getJSON("/js/content.json", function (data) {
$(".lander .title").text(data.lTitle);
$(".lander .subtitle").text(data.lSubtitle);
$(".lander .text").html(data.lText).split('\n').join('<br/>');
});
JSON 文件:
{
"comment": "Landing page",
"lTitle": "Your webpage",
"lSubtitle": "Your webpage subtitle",
"lText": "Edit this text under >js/content.json< ",
"lDetailsTitle": "Here goes the details title under the landing header.",
"lDetailsText": "Here goes the details text."
}
我要做的是使用$parseJSON 检查整个content.json 是否有效(不仅仅是一个字符串)。我想这样做的原因是 jquery 可以在 DOM 中显示错误消息,以便用户知道为什么 divs 中没有文本。
我试过了,但它不起作用:
var isValid = jQuery.parseJSON("/js/content.json");
if (isValid === true) {} else {
$("#overlayMessage").css("display", "block");
$("#overlayMessage .title").text("Oh no, we can't display this page!");
$("#overlayMessage .text").text("An error occured with the file under: 'js/content.json'. Reason: Invalid.");
}
这有可能吗,还是只能检查一个字符串是否有效?
【问题讨论】:
标签: javascript jquery json