【发布时间】:2016-07-01 13:54:58
【问题描述】:
我是一个初学者,在一个简单的前端项目中测试 getJSON。我了解到我不能使用我之前一直使用的 file:// URL 前缀,并且必须模拟服务器(这是正确的吗?)。我通过在我的项目目录中的终端 (OS X) 中键入 python3 -m http.server 8000 来利用 Python 的内置服务器功能。
我现在可以在浏览器中输入http://0.0.0.0:8000/,它会加载我的 index.html。我还有另外两个文件:app.js 和 aceOfSpades.json,它们位于一个名为 javascripts 的文件夹中,与 index.html 位于同一级别。
加载 index.html 时,控制台中显示的唯一值是“hello world”。这告诉我 app.js 正在正确加载,但 getJSON 函数是(1)没有看到 aceOfSpades.json 文件,(2)看到文件但没有将其对象放入“card”参数中,或者( 3) 可能会陷入我的 Python 内置服务器。也许这完全是另外一回事。
当我查看 Chrome 开发者面板的“源”选项卡时,javascripts 文件夹中列出的唯一文件是 app.js。 aceOfSpades.json 无处可寻!
我的问题:为什么我的 JSON 对象没有在给定以下代码的情况下打印到控制台?我该如何解决这个问题?谢谢。
index.html:
<!doctype html>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script src="javascripts/app.js"></script>
</body>
</html>
app.js:
var main = function () {
"use strict";
$.getJSON("/javascripts/aceOfSpades.json", function (card) {
console.log("your card should appear after this");
console.log(card);
});
console.log("hello world");
};
$(document).ready(main);
aceOfSpades.json:
{
rank: "ace",
suit: "spades"
}
【问题讨论】:
-
你至少在控制台中得到""你的卡片应该出现在这个之后""吗?这是相对重要的信息。
-
不,唯一出现的是“hello world”
-
然后添加一个错误处理程序。它可能会告诉你“parseerror”。 parseerror 是什么意思?
-
我熟悉 Python 中的错误处理,但不熟悉 JavaScript。我应该尝试实现 try/catch/throw 吗?
-
由于这是一个返回 jqXHR 的 jQuery ajax 方法,您可以使用 .fail 方法。
.fail(function (jqXHR, textstatus, message) {/* log all three */});api.jquery.com
标签: javascript jquery html json