2012-03-06 55 views
0

我有连接到服务器的Jquery + Ajax页面获取一些数据并显示它。这是始终完成的,函数在完成所有任务后自动调用并开始执行一次又一次。但是如果计算机失去互联网连接,一切都会停止。当连接再次返回时,没有任何反应。这里是JavaScript代码。我怎样才能解决它,所以它会继续工作后连接又回来了。如果连接丢失,javascript不会重新连接到服务器端

$(document).ready(function() { 
var a=1; 
var max='23'; 

function kiosk() 
{ 
    if(a<max) 
    { 
     $.post('engine.php', { index: a }, 
     function(result) 
     { 
      result = jQuery.parseJSON(result); 

      $('#main').css({'display':'none'}); 


      $('#div_city').html(result.dest); 
      $('#div_price').html(result.price); 
      $('#div_price_pre').html('From&nbsp;'); 
      $('#div_price_after').html('&nbsp;Euro'); 

       $('#main').fadeIn(2000).delay(3000).fadeOut(2000, function() 
        { 

          $('#main').hide; 
          a++; 
          kiosk(); 


        }); 

     }); 
    } 
    else 
    { 
     a=1; 
     kiosk(); 
    } 

} 
kiosk(); 
}); 

回答

3

我会建议,而不是使用$使用。员额

$阿贾克斯({类型: “后”,成功:功能1(),失败:函数2()}。

在函数2( 。)您可以将超时后再次拨打koisk和succces将您已经创建,现在的功能

此链接将帮助您了解AJAX功能jQuery Ajax error handling, show custom exception messages

EG码片段:

function kiosk() 
{ 
if(a<max) 
{ 
    $.ajax({type : "POST" , url : 'engine.php',data: { index: a }, 
    success : function(result) 
    { 
     result = jQuery.parseJSON(result); 

     $('#main').css({'display':'none'}); 


     $('#div_city').html(result.dest); 
     $('#div_price').html(result.price); 
     $('#div_price_pre').html('From&nbsp;'); 
     $('#div_price_after').html('&nbsp;Euro'); 

      $('#main').fadeIn(2000).delay(3000).fadeOut(2000, function() 
       { 

         $('#main').hide; 
         a++; 
         kiosk(); 


       }); 

    },error : function (xhr, ajaxOptions, thrownError){ setTimeout(200,kiosk()) } 

    }); 
} 
else 
{ 
    a=1; 
    kiosk(); 
} 

} kiosk(); });`

+0

我认为这是正确的,但我收到语法错误 – David 2012-03-06 11:56:02

+0

是我的错。一切正常。谢谢!!! – David 2012-03-06 12:08:18

-1

由于我认为它会抛出异常,因此脚本中断。你可以添加你的代码尝试和catch块,即使有错误,你可以继续尝试。

try { 
    result = jQuery.parseJSON(result); 
    // do your work 
} catch { 
    // call function again 
} 

或者你可以使用,jQuery的ajax,它有一个onerror事件。

0

使用jQuery.post您传递的回调仅在成功时执行。 您应该使用具有不同回调的jQuery.ajax。请参阅documentationcomplete,successerror回调。

您甚至可以使用statusCode将特定的HTTP代码映射到自定义函数。

相关问题