这似乎非常不方便,当返回的数据不是有效的JSON时,jQuery的
$.getJSON
静默失败。为什么这是实现无声故障?什么是执行getJSON更好的失败行为(例如抛出异常,console.log()或其他)的最简单的方法?
解决方法
您可以使用
function name() { $.getJSON("",function(d) { alert("success"); }).done(function(d) { alert("done"); }).fail(function(d) { alert("error"); }).always(function(d) { alert("complete"); }); }
如果您想查看错误的原因,请使用完整版本
function name() { $.getJSON("",function(d) { alert("success"); }).fail( function(d,textStatus,error) { console.error("getJSON Failed,status: " + textStatus + ",error: "+error) }); }
如果你的JSON格式不正确,你会看到类似的
getJSON Failed,status: parsererror,error: SyntaxError: JSON Parse error: Unrecognized token '/'
如果URL错误,你会看到类似的
getJSON Failed,status: error,error: Not Found
如果你试图从另一个域获取JSON,违反Same-origin policy,这种方法返回一个空消息。请注意,您可以使用JSONP(其为limitations)或跨源资源共享(CORS)的首选方法来解决同源策略。