【发布时间】:2015-11-12 10:54:02
【问题描述】:
我有一个从 JSON 文件中获取数据的 jQuery 函数,但我无法让它工作。我正在括号编辑器中开发,当我在他们的实时预览中打开网站时,一切都很好。但是当我在本地打开 html 文件时,会执行 $.getJSON.error 而不是正常的 $.getJSON
function loadJson(e)
{
$('.images').fadeOut(300);
var jsonURL = "../../../images.json";
var txt = $(e.target).text();
setTimeout(function ()
{
$('.images').empty();
$.getJSON(jsonURL, function(json)
{
var imgList = "";
$.each(json[txt], function ()
{
imgList += '<div class="image_container reference">
<a href="' + this.imgPath + '">
<img src="' + this.imgPath + '"/>
<div class="overlay">
<span>' + this.name + '</span>
</div>
</a>
</div>';
});
$('.images').append(imgList);
}).error(function(json) { alert("error"); });
}, 300);
$('.images').fadeIn(300);
}
函数获取点击的项目标签,将其与 JSON 文件中的数组名称匹配,然后分别将这些图像附加到容器中。当我在 Brackets 实时预览中运行它时,它按预期工作,所以我真的不知道发生了什么?
【问题讨论】:
-
just stops working,gives me error- 什么错误? -
应该是您的 json 文件路径的问题。它能够在使用括号时解析相对路径,但在浏览器中它无法这样做
-
$.getJSON(jsonURL, function(json) {}).error(function(json) {});被执行而不是正常的 $.getJSON -
将您的 json url 替换为该文件的确切地址而不是路径
-
when I open html file locally...- 这就是你的问题。来自file://的任何ajax 请求都被视为跨域请求,您不能这样做。您需要它在 Web 服务器上运行,所以一切都在域或本地主机上。
标签: javascript jquery html json