带有超时的jQuery getJSON

当打电话给雅虎网络服务(http://boss.yahooapis.com/ysearch)以返回数据集时,是否可以设置超时并在程序结束后退出例程?

jQuery.getJSON("http://boss.yahooapis.com/ysearch/...etc", function (data) { //result set here }); 

您可以使用超时选项

http://api.jquery.com/jQuery.ajax/

 $.ajax({ url: url, dataType: 'json', data: data, success: callback, timeout: 3000 //3 second timeout }); 
  $.ajax({ url: url, dataType: 'json', data: data, success: callback, timeout: 3000 //3 second timeout, error: function(jqXHR, status, errorThrown){ //the status returned will be "timeout" //do something } }); 
  function testAjax() { var params = "test=123"; var isneedtoKillAjax = true; // set this true // Fire the checkajaxkill method after 10 seonds setTimeout(function() { checkajaxkill(); }, 10000); // 10 seconds // For testing purpose set the sleep for 12 seconds in php page var myAjaxCall = jQuery.getJSON('index2.php', params, function(data, textStatus){ isneedtoKillAjax = false; // set to false // Do your actions based on result (data OR textStatus) }); function checkajaxkill(){ // Check isneedtoKillAjax is true or false, // if true abort the getJsonRequest if(isneedtoKillAjax){ myAjaxCall.abort(); alert('killing the ajax call'); }else{ alert('no need to kill ajax'); } } } 

Galen提出的超时选项是最好的方法。 如果您需要备用方法,则可以记录请求启动的时间,并在回调中将其与当前时间进行比较。 如果已经过了一定的时间,则忽略结果。 当然这不会取消请求。