Показывать загрузку изображения во время публикации с помощью ajax - PullRequest
29 голосов
/ 24 марта 2010

Я знаю, что в Интернете есть тысячи примеров, но я хочу, чтобы для сценария мне уже приходилось отображать изображение загрузки gif во время получения данных. Мои знания Java плохие, поэтому я спрашиваю, как изменить следующее:

<script type="text/javascript"> 
 $(document).ready(function(){
  function getData(p){
    var page=p;
    $.ajax({
        url: "loadData.php?id=<? echo $id; ?>",
        type: "POST",
        cache: false,
        data: "&page="+ page,
        success : function(html){
            $(".content").html(html);
        }
    });
}
getData(1);

$(".page").live("click", function(){
    var id = $(this).attr("class");
    getData(id.substr(8));
        });
      });
  </script> 

И мой div здесь:

    <div class="content" id="data"></div>

Спасибо. John

Ответы [ 7 ]

61 голосов
/ 24 марта 2010

Допустим, у вас есть тег где-то на странице, который содержит ваше загрузочное сообщение:

<div id='loadingmessage' style='display:none'>
  <img src='loadinggraphic.gif'/>
</div>

Вы можете добавить две строки к вашему вызову ajax:

function getData(p){
    var page=p;
    $('#loadingmessage').show();  // show the loading message.
    $.ajax({
        url: "loadData.php?id=<? echo $id; ?>",
        type: "POST",
        cache: false,
        data: "&page="+ page,
        success : function(html){
            $(".content").html(html);
            $('#loadingmessage').hide(); // hide the loading message
        }
    });
9 голосов
/ 20 июня 2013
$.ajax(
{
    type: 'post',
    url: 'mail.php',
    data: form.serialize(),
    beforeSend: function()
    {
        $('.content').html('loading...');
    },
    success: function(data)
    {
        $('.content').html(data);
    },
    error: function()
    {
        $('.content').html('error');
    }
});

весело играть в Arround!

если у вас должно быть быстрое время загрузки, которое мешает отображению загрузки, вы можете добавить какое-то время ожидания.

9 голосов
/ 24 марта 2010

Взгляните на ajaxStart и ajaxStop

2 голосов
/ 29 ноября 2013

Это очень просто и легко управлять.

jQuery(document).ready(function(){
jQuery("#search").click(function(){
    jQuery("#loader").show("slow");
    jQuery("#response_result").hide("slow");
    jQuery.post(siteurl+"/ajax.php?q="passyourdata, function(response){
        setTimeout("finishAjax('response_result', '"+escape(response)+"')", 850);
            });
});

})
function finishAjax(id,response){ 
      jQuery("#loader").hide("slow");   
      jQuery('#response_result').html(unescape(response));
      jQuery("#"+id).show("slow");      
      return true;
}
1 голос
/ 07 мая 2014
<div id="load" style="display:none"><img src="ajax-loader.gif"/></div>

function getData(p){
        var page=p;
        document.getElementById("load").style.display = "block";  // show the loading message.
        $.ajax({
            url: "loadData.php?id=<? echo $id; ?>",
            type: "POST",
            cache: false,
            data: "&page="+ page,
            success : function(html){
                $(".content").html(html);
        document.getElementById("load").style.display = "none";
            }
        });
0 голосов
/ 08 ноября 2016

обязательно измените в вызове ajax

async: true,
type: "GET",
dataType: "html",
0 голосов
/ 15 октября 2016

//$(document).ready(function(){
//	 $("a").click(function(event){
//		event.preventDefault();
//		$("div").html("This is prevent link...");
//	});
//});			

$(document).ready(function(){
	$("a").click(function(event){
		event.preventDefault();
		$.ajax({
			beforeSend: function(){
				$('#text').html("<img src='ajax-loader.gif' /> Loading...");
			},
			success : function(){
				setInterval(function(){ $('#text').load("cd_catalog.txt"); },1000);
			}
		});
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
		
<a href="http://www.wantyourhelp.com">[click to redirect][1]</a>
<div id="text"></div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...