I need to preload ajax data before attaching it to a div and for that I have this code:
$.ajax({
url: 'ajax.php',
data: { modelID:id },
type: 'post',
success: function(result){
$(result).load(function(){
$('.view_'+id).html(result)
$('.view_'+id).find('.brandModelGallery').bxSlider({})
$('.view_'+id).addClass('loaded')
})
}
})
And this doesn't return anything. If write it as $('.view_'+id).load(result)
then I can see all the contents of result
in console as a syntax error so it fetches them alright, but not this way. Why is that?
I've create an example on jsfiddle
Html:
<div id="d1"></div>
<div id="d2"></div>
js:
$.ajax({
url: './',
data: { modelID: '1' },
type: 'post',
success: function(result){
console.log(result);
$('#d1').html(JSON.stringify(result));
// A fake object as your result.
var bxSlider = $('<ul class="bxslider"><li><img src="https://i.imgur.com/KsV6jS5.png" /></li><li><img src="https://i.imgur.com/bqcK47I.png" /></li></ul>');
// Do thing only when all img loaded.
var unLoadimges = bxSlider.find("img").length;
bxSlider.find('img').load(function() {
--unLoadimges;
console.log("loaded, left: " + unLoadimges);
if (unLoadimges === 0) {
bxSlider.appendTo($("#d2")).bxSlider();
}
});
}
})
When you append img
element to your page, it doesn't mean its loaded. Listen to its load
event.
Edit: Just make the bxSlider works on my example now. Not sure if there's a better way to check whether all images loaded or not.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.