Neste post vou explicar como exibir a mensagem de “carregando” nas requisições ajax:
Podemos fazer de 2 formas:
1 – Antes da requisição nós exibimos o “loading” e depois da conclusão nós ocultamos;
2 – Fazer isso de maneira automática (é o que vamos ver neste post).
Vamos criar nossa div que será o loading:
<div class="carregando"> <strong>CARREGANDO</strong> </div>
O CSS da div:
.carregando { width: 250px; height: 20px; top: 50%; left: 50%; margin: -10px 0 0 -125px; position: fixed; z-index: 9999; display: none; } .carregando strong { font-size: 12px; text-align: center; float: left; display: block; width: 100%; color: red }
A ideia aqui é só mostrar o conceito, por isso não estou me preocupando com formatação do CSS.
Feito isso vamos setar para que a cada requisição ajax ele exiba nosso loading, assim como no término do request ele oculte a div.
$(document).ready(function() { $(".carregando").ajaxStart(function(){ $(this).fadeIn(300); }); $(".carregando").ajaxStop(function(){ $(this).fadeOut(200); }); });
O código completo de teste ficou assim:
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script> $(document).ready(function() { $(".carregando").ajaxStart(function(){ $(this).fadeIn(300); }); $(".carregando").ajaxStop(function(){ $(this).fadeOut(200); }); $("#botao").click(function(){ $.ajax({ type: "POST", url: "index.html", success: function( data ) { console.log( data ); } }); }); }); </script> <style> .carregando { width: 250px; height: 20px; top: 50%; left: 50%; margin: -10px 0 0 -125px; position: fixed; z-index: 9999; display: none; } .carregando strong { font-size: 12px; text-align: center; float: left; display: block; width: 100%; color: red } </style> </head> <body> <input type="button" id="botao" value="carregar"/> <div class="carregando"> <strong>CARREGANDO</strong> </div> </body> </html>
Até a próxima.