这是一个简单的工作示例,它读取两个本地数据文件,并将结果附加到显示卡片的DOM,然后是表示一手卡片的无序列表。
app.js
var main = function() {
"use strict";
$.getJSON("cards/aceOfSpades.json", function (data) {
// create an element to hold the data
var $cardParagraph = $("<p>");
console.log("STUBB");
// create the
$cardParagraph.text(data.rank + " of " + data.suit);
// append the card paragraph to main
$("main").append($cardParagraph);
});
$.getJSON("cards/hand.json", function (hand) {
var $list = $("<ul>");
// hand is an array, so we can iterate over it
hand.forEach(function (data) {
// create a list item to hold the card
// and append it to the list
var $card = $("<li>");
$card.text(data.rank + " of " + data.suit);
$list.append($card);
});
// append the list to main
$("main").append($list);
});
};
$(document).ready(main);
hand.json
[
{ "suit" : "spades", "rank" : "ace" },
{ "suit" : "hearts", "rank" : "ten" },
{ "suit" : "spades", "rank" : "five" },
{ "suit" : "clubs", "rank" : "three" },
{ "suit" : "diamonds", "rank" : "three" }
]
模仿这一点,我的代码尝试读取具有类似JSON记录数组的文件:
checkBoxesA.json
[
{
"label": "New provider",
"note": "check if the applicant is not currently enrolled in the Medi-Cal
program as a provider with an active provider number. Include
the NPI (or Denti-Cal provider number if applicable) for the
business address indicated in item 4. "
},
{ "label": "Change of business address",
"note": "check if the applicant is currently enrolled in the Medi-Cal
program and is requesting to relocate to a new business address
and vacate the old location. Indicate the business address
applicant is moving from."
},
. . .
]
这是不起作用的javaScript。 STUBB1没有打印到控制台,因此忽略$.getJSON
?
var main = function () {
"use strict";
console.log("Hello World!");
$.getJSON("checkBoxesA.json", function (entry) {
var $list = $("<ul>");
console.log("STUBB1!");
entry.forEach(function(entry){
var $entry =$("<li>");
$entry.text(entry.label + " of " + entry.text);
$list.append($entry);
});
$("main").append($list);
});
console.log("STUBB2!");
};
$(document).ready(main);
答案 0 :(得分:0)
STUBB1没有打印到控制台,因此忽略$ .getJSON?
不予理睬。这可能是一个糟糕的请求但你不知道,直到你添加代码来处理错误条件(或只是在浏览器&#39;控制台)。毕竟,$.getJSON
是异步的。我建议只在网站上阅读http://api.jquery.com/jquery.getjson/,他们有一些例子。
答案 1 :(得分:0)
(1)Google Chrome上的JavaScript无法读取本地JSON数据文件,除非在Chrome完全关闭后发出此shell命令。
打开-a Google \ Chrome --args --allow-file-access-from-files
这将启动一个免于限制此类文件访问的新浏览器。
您无需为Safari或Firefox执行任何操作。
(2)JSON文件中的文本需要正确形成,没有嵌套的双引号或单引号!
所以事后才能解决我的问题。