开发者

How to wait for image load from ajax() success data?

开发者 https://www.devze.com 2023-02-23 13:18 出处:网络
I have jquery ajax() function: $.ajax({ type: \"POST\", url: \'ajax.php\', data: \'url=\'+variable, success: function(data){

I have jquery ajax() function:

$.ajax({
    type: "POST",
    url: 'ajax.php',
    data: 'url='+variable,
    success: function(data){
        $('#mydiv').h开发者_JS百科tml(data);
    }
}); 

My ajax response (data variable) is similar to this:

<a id="90" href="mylink"><img src="myimagelink90.jpg" /></a>
<a id="91" href="mylink"><img src="myimagelink91.jpg" /></a>
<a id="92" href="mylink"><img src="myimagelink92.jpg" /></a>
<a id="93" href="mylink"><img src="myimagelink93.jpg" /></a>
<a id="94" href="mylink"><img src="myimagelink94.jpg" /></a>
<a id="97" href="mylink"><img src="myimagelink97.jpg" /></a>
<a id="98" href="mylink"><img src="myimagelink98.jpg" /></a>
<a id="120" href="mylink"><img src="myimagelink120.jpg" /></a>
<a id="121" href="mylink"><img src="myimagelink121.jpg" /></a>
<a id="122" href="mylink"><img src="myimagelink122.jpg" /></a>
<a id="123" href="mylink"><img src="myimagelink123.jpg" /></a>
<a id="124" href="mylink"><img src="myimagelink124.jpg" /></a>
<a id="125" href="mylink"><img src="myimagelink125.jpg" /></a>

So my question is: what's the easiest way to wait for myimagelink#.jpg are all loaded?


Try using the load() function. In this case, you'll need to bind it using the live() handler, as the images are dynamically being loaded:

var loaded = 0;

$('#mydiv a img').live('load', function()
{
  loaded++;

  if (loaded == $('#mydiv a img').length)
  {
    alert('All of the images have loaded.');
  }
});

There might be a more efficient way to do this, so feel free to say how slow this might work.


You would have to put an "onload" event on each, increment some counter and see if it matches the number of images you've inserted.


Are you loading the images dinamically, and want to display after they load?

While 'data' is a javascript variable that contains the strings, your images ain't going to load...

To load the images before inserting them to the page, you'll have to make them dom elements.

Don't know if it's the best option, but i think this works:

$.ajax({
    type: "POST",
    url: 'ajax.php',
    data: 'url='+variable,
    success: function(data){
        $('<div />').html(data).load(function(){
            $(this).appendTo("#myDiv");
        })
}); 


Something like:

$.ajax({
  type:"POST",
  url: "ajax.php",
  dataType: "application/x-www-form-urlencoded",
  data: "url=" + variable,
  async: true,
  beforeSend : function(){
    $("#Loading").show(); //show image loading
  },
  success: function(msg){
    $("#LoadingPiloto").hide(); //hide image loading
  }
})
0

精彩评论

暂无评论...
验证码 换一张
取 消