为什么我使用.getJSON不一致地阅读本地JSON文件?
下面是一个简单的工作示例,上面写着两个本地数据文件并追加结果到DOM显示卡,然后代表一手牌的无序列表。为什么我使用.getJSON不一致地阅读本地JSON文件?
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);
STUBB1不打印到控制台,这样$ .getJSON被忽略?
不容忽视。它可能会提出错误的请求,但是直到您添加代码来处理错误情况(或者只是在浏览器的控制台中查看),您才会知道。毕竟,$.getJSON
是异步的。我建议只在http://api.jquery.com/jquery.getjson/上阅读,他们有一些例子。
无论哪种情况,都没有错误记录到控制台,只是从编程存根输出,并且在第一种情况下显示扩展DOM。 – user2970900 2014-12-04 18:16:23
(1)谷歌浏览器的JavaScript无法读取本地JSON数据文件,除非Chrome浏览器后发出了这样的shell命令完全关闭。
开放-a谷歌\ Chrome的--args --allow-文件访问从档案
这将启动一个新的浏览器是从限制这样的文件访问豁免。
你不必做任何本作Safari或Firefox。
(2)在JSON文件中的文本需要与没有嵌套双或单引号正确地形成!
因此,这在事后解决了我的问题。
我澄清了这个问题! – user2970900 2014-12-03 17:37:43
运行此代码的结果在以下两种情况之间变化:(1)在任一示例中记录无控制台错误,并在第一种情况下显示来自第一个(成功)示例的DOM修改。在另一种情况下,我得到(2)控制台日志错误。 – user2970900 2014-12-04 18:09:28