从 ajax 捕获数据并对其进行操作的最佳方式

Best way to capture data from ajax and manipulate with it

本文关键字:操作 方式 最佳 ajax 数据      更新时间:2023-09-26

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

  1. 图像网址从管理员保存到数据库
  2. 前端脚本对 PHP 文件进行 ajax 调用,并从数据库返回所有 URL。
  3. 现在,当我拥有所有图像时,可以应用轮播插件。
  4. 现在正在逐个显示图像。

诀窍是我想在显示最后一个图像时进行另一个 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 成功时,轮播插件开始旋转 imgs,完成后,应再次调用get_images函数。但是这个函数已经在另一个函数中了,每次调用时,它都会更深一层。有什么办法可以做到这一点吗?

最好是轮播触发一个需要更多图像的事件并收听该事件。然后,您可以检索更多图片并将新列表返回到轮播。有一些轮播插件内置了所有这些。我经常使用这个:http://caroufredsel.dev7studios.com/<</p>

div class="answers">

也许在你的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();

此轮播对象将在实例化时请求图像数组,并以 5 秒的间隔显示每个图像。当所有映像都用尽时,它将自动进行另一个 AJAX 调用,以与原始相同的方式检索图像,然后继续循环遍历新映像。它将永远在这个循环中继续下去。