我知道已经有一段时间没有人在这里回答了,发帖人可能已经从这里或其他地方得到了他的回答。然而,我确实认为这篇文章将帮助任何寻找在执行 getJSON 请求时跟踪错误和超时的方法的人。因此,下面是我对问题的回答
getJSON 结构如下(见http://api.jqueri.com):
$(selector).getJSON(url,data,success(data,status,xhr))
大多数人使用
$.getJSON(url, datatosend, function(data){
//do something with the data
});
他们使用 url var 提供指向 JSON 数据的链接,datatosend 作为添加 "?callback=?" 和必须发送的其他变量以获取返回的正确 JSON 数据的位置,以及成功函数为处理数据的函数。
但是,您可以在成功函数中添加状态和 xhr 变量。 status 变量包含以下字符串之一:“success”、“notmodified”、“error”、“timeout”或“parsererror”,xhr 变量包含返回的 XMLHttpRequest 对象
(found on w3schools)
$.getJSON(url, datatosend, function(data, status, xhr){
if (status == "success"){
//do something with the data
}else if (status == "timeout"){
alert("Something is wrong with the connection");
}else if (status == "error" || status == "parsererror" ){
alert("An error occured");
}else{
alert("datatosend did not change");
}
});
通过这种方式,可以轻松跟踪超时和错误,而无需实现在请求完成后启动的自定义超时跟踪器。
希望这对仍在寻找这个问题的答案的人有所帮助。