我正在制作一个应该从ajax数据库获取图像,然后用一些carousel插件显示它。以下是它应该如何工作:
诀窍是我想在显示最后一张图像时再进行一次ajax调用,并使用数据库中的新图像重新填充容器div。这是我的代码
function get_images(){
var data = {
"function_name" : "get_images",
"args" : ""
};
$.ajax({
type : "POST",
url : "http://localhost/.../functions.php",
data : data,
dataType : "JSON",
success : function(ret){
$(".container").html(ret);
$(".container").carousel(//When last call - function again);
}
});
}
这就是问题所在。在ajax成功carousel插件开始旋转imgs,当它完成时,应该再次调用get_images函数。但是这个函数已经在另一个函数中了,每次调用时它都会更深一层。有没有办法做到这一点?
答案 0 :(得分:1)
最好是旋转木马发射需要更多图像的事件并听取该事件。然后,您可以检索更多图像并将新列表返回到轮播。有旋转木马插件,所有这些内置。我经常使用这个:http://caroufredsel.dev7studios.com/
答案 1 :(得分:1)
也许在你的PHP脚本中:
<?php
if ( isset($_POST['function_name']) ) {
if ( $_POST['function_name'] == 'get_images' ) {
// Get some URLs into an array...
// For the sake of the example we'll manually fill the array
$urls = ['img/image1.png', 'img/image2.png'];
echo json_encode($urls);
}
}
在你的JS中:
function Carousel() {
this.getMoreImages();
}
Carousel.prototype.nextImage = function () {
if (this.i < this.images.length) {
this.showImage(); // Implement this.
this.i += 1;
this.spin():
}
else {
this.getMoreImages();
}
}
Carousel.prototype.spin = function () {
var self = this;
setTimeout(function () {
self.nextImage();
}, 5000);
}
Carousel.prototype.getMoreImages = function () {
var self = this;
$.ajax({
type : 'POST',
url : 'http://localhost/.../functions.php',
data : data,
dataType : 'JSON',
success : function (ret) {
self.images = JSON.parse(ret);
self.i = 0;
self.spin();
}
});
}
var myCarousel = new Carousel();
此Carousel对象将在实例化时请求一组图像,并以5秒的间隔显示每个图像。当所有图像都已耗尽时,它将自动进行另一次AJAX调用,以与原始图像相同的方式检索图像,然后继续循环显示新图像。它将永远在这个循环中继续。