使用 .ajax() 获取 JSON 时出现未知错误

4

好的,我正在尝试使用以下jQuery代码从URL获取JSON文件。

$.ajax({
    url: 'http://example.com/example.json',
    dataType: 'json',
    type: 'GET',
    async: true,
    cache: true,
    crossDomain: true
});

然而,当请求触发时,Firebug会提示发生了一个错误,但不告诉我是什么错误。

我可以在浏览器中轻松访问URL,并且JSON是完全有效的(根据http://www.freeformatter.com/json-validator.html)。

有什么建议吗?

编辑:

好的,将contentType更改为jsonp已经让我更进一步了。我的JSON看起来像这样(http://pastebin.com/hSAP30zv),但是Firebug正在说:

SyntaxError: invalid label
"item" : {
^

还有其他建议吗?


在Chrome上进行测试并检查控制台,也许错误信息会更准确。 - A. Wolff
你希望如何实现 crossDomain?如果你想使用 JSONP,你需要发出一个 JSONP 响应而不是 JSON。如果你使用 CORS,你应该传递 xhrFields: { withCredentials: true } (http://api.jquery.com/jQuery.ajax/)。 - Matt
1
我不确定 dataType: 'json'crossDomain: true 是否能很好地配合使用。只有在您想要在相同的域上强制执行跨域行为时,才需要使用 crossDomain: true。因此,我假设您实际上确实发出了一个返回JSON的跨域请求。这将无法正常工作,除非服务器支持CORS。或者它必须返回JSONP,并且您必须告诉jQuery使用 dataType: 'jsonp' 来期望JSONP。 - Felix Kling
dataType: 'jsonp'做到了。现在它在解析JSON时出现了问题? - Nathan McCallum
因为服务器似乎没有返回JSONP。如果服务器不支持跨域请求,则无法进行跨域请求。正如我所说,它必须支持CORS,这样它就像在同一域上的服务器一样工作,或者它必须返回JSONP,这与JSON不同。这就是你得到错误的原因。如果您无法控制服务器,则必须在您的端上创建代理,即通过Ajax连接到您的服务器,并让服务器向外部服务器发出请求。 - Felix Kling
但是如果我尝试使用标准的GET方法,我会再次收到相同的未指定错误... - Nathan McCallum
2个回答

4
这个错误处理程序可能会帮到您:
$.ajax({
    url: 'http://example.com/example.json',
    dataType: 'json',
    type: 'GET',
    async: true,
    cache: true,
    success: function (html) {
        alert('successful : ' + html);
    },
    error: function (jqXHR, exception) {
        if (jqXHR.status === 0) {
            alert('Not connect.\n Verify Network.');
        } else if (jqXHR.status == 404) {
            alert('Requested page not found. [404]');
        } else if (jqXHR.status == 500) {
            alert('Internal Server Error [500].');
        } else if (exception === 'parsererror') {
            alert('Requested JSON parse failed.');
        } else if (exception === 'timeout') {
            alert('Time out error.');
        } else if (exception === 'abort') {
            alert('Ajax request aborted.');
        } else {
            alert('Uncaught Error.\n' + jqXHR.responseText);
        }
    },
    crossDomain: true
});

1
尝试处理函数 fail 的错误:
$.ajax({
    url: 'http://example.com/example.json',
    dataType: 'json',
    type: 'GET',
    async: true,
    cache: true,
    crossDomain: true
}).fail(function(jqXHR, textStatus) {
  alert( "Request failed: " + textStatus );
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接