从ajax捕获数据并使用它进行操作的最佳方法

时间:2013-09-29 21:29:50

标签: javascript jquery ajax

我正在制作一个应该从ajax数据库获取图像,然后用一些carousel插件显示它。以下是它应该如何工作:

  1. 图片网址从管理员
  2. 保存到数据库
  3. 前端脚本对php文件进行ajax调用,并从db返回所有url。
  4. 现在,当我拥有所有图像时,可以应用轮播插件。
  5. 图像现在逐一显示。
  6. 诀窍是我想在显示最后一张图像时再进行一次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函数。但是这个函数已经在另一个函数中了,每次调用时它都会更深一层。有没有办法做到这一点?

2 个答案:

答案 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调用,以与原始图像相同的方式检索图像,然后继续循环显示新图像。它将永远在这个循环中继续。