Shefarol Soluções Web

AJAX - Carregando arquivos - Voltar

Carrega arquivos externos ao clicar nos links e mostra uma imagem enquanto carrega cada arquivo, caso o arquivo a ser carregado não seja encontrado, uma mensagem aparecerá avisando do ocorrido.

 

Arquivo 1 | Arquivo 2 | Arquivo 3

 

Código em HTML
<div class="float-right">
	<a href="ajax1.html" class="link">Arquivo 1 |
	<a href="ajax2.html" class="link">Arquivo 2 |
	<a href="ajax3.html" class="link">Arquivo 3
</div>

 

Abaixo o exemplo do arquivo em javascript:

Código em Javascript (Ajax)
$(document).ready(function() {
			
	$('.link').click(function(e) { 
		e.preventDefault(); 

		$('<div class="overlay"></div>').appendTo('body');
		$('body').append('<img id="carregando" src="img/loading.gif" alt="Carregando..." />');
		        
		var url = $(this).attr('href'); 

		$.ajax({
		    url: url, 
		    dataType: 'html', 
		    beforeSend: function() {
                $('#carregando').show(); 
                $('#dados').css('visibility', 'hidden');
            },
		    success: function(response) {
		        $('#dados').html(response); 
		    },
		    error: function(xhr, status, error) {
                $('#dados').html('<p class="erro"><b><i>Ocorreu um erro ao carregar o arquivo: ' + error + '</i></b></p>');
            },
		    complete: function() {
                setTimeout(function() {
		            $('#carregando').fadeOut(function(){
		                $(this).remove();
		            });
		            $('.overlay').fadeOut(function(){
		                $(this).remove();
		            });
		            $('#dados').css('visibility', 'visible');
		        }, 500);
            }
		});
	});
});