gpt4 book ai didi

javascript - JSON 未被 $.getJSON 抓取

转载 作者:行者123 更新时间:2023-12-01 03:32:33 25 4
gpt4 key购买 nike

最终解决方案:我的 .json 文件的格式存在问题,比我包含的代码段更深入的问题。现在一切正常。非常感谢评论中的每个人,我将 @TWLATL 的答案标记为正确,因为它是一个格式良好的函数解决方案,我可以在以后的项目中使用。

我正在尝试从 script.js 访问我的 data.json 文件(均位于 root 目录中),但没有成功似乎根本没有运行。在进行错误处理之前,我没有收到该函数已运行的任何指示。感谢评论,我将 .error 替换为 .fail,但我仍然不明白为什么失败。

index.html

<body>
<h1>JSON Render</h1>
<div id="fileViewer"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>

script.js

$.getJSON('data.json', function(data) {
console.log('json grabbed')
console.log(data);
})
.fail(function(data) {
console.log("GetJSON Error!");
console.log(data);
});

$.ajax({
url: 'data.json',
dataType: 'json',
success: function( data ) {
console.log( "SUCCESS: " );
console.log( data );
},
error: function( data ) {
console.log( "AJAX ERROR: " );
console.log( data );
}
});

data.json(示例)

{
"children": [
{
"name": "Main Folder",
"type": "folder"
},
{
"name": "Private folder",
"type": "folder"
}
]
}

我一直在 Stack Overflow 上四处寻找,但没有找到解决我的问题的解决方案。救命!

编辑:将 jQuery CDN 添加到我的 index.html 中。它就在那里。我只是忘了把它放在问题中。

编辑 2:更新了 script.js 以反射(reflect)返回下面屏幕截图的代码。 (屏幕截图在对象中间被 chop 。如果对象的上下文确实相关,我可以包含更多内容。) console output

编辑 3:新的 AJAX 错误处理:新的ajax功能:

$.ajax({
url: 'data.json',
dataType: 'json',
success: function( data ) {
console.log( "SUCCESS: " );
console.log( data );
},
error: function(data, textStatus, errorThrown) {
console.log("textStatus: ",textStatus);
console.log("errorThrown: ",errorThrown);
}
});

我现在奇妙地得到了这个控制台输出: new console output

最佳答案

使用稍微修改过的代码版本,我可以很好地返回 JSON:

http://plnkr.co/edit/DMLyJa1Quj7ofszn5Y7o?p=info

$(document).ready(function() {
console.log("ready!");

var items;

$.getJSON('data.json', function(data) {
console.log('json grabbed');
})
.done(function(data) {
items = data.children;
console.log(items);
})
.fail(function(data) {
console.log("Error!");
});

}); // close document.ready

Jquery 现在使用 .done 作为成功方法。在该 block 中,只需将您的 data.children 项分配给一个变量即可。

关于javascript - JSON 未被 $.getJSON 抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44465082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com