Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/452.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery$.getJSON和通过数组的循环正在全部转储_Javascript_Php_Jquery_Json_Laravel - Fatal编程技术网

Javascript jQuery$.getJSON和通过数组的循环正在全部转储

Javascript jQuery$.getJSON和通过数组的循环正在全部转储,javascript,php,jquery,json,laravel,Javascript,Php,Jquery,Json,Laravel,这是我当前的JS代码: $(function(){ $.getJSON("/get_slideshow_messages", function(data){ setInterval(function(){ $.each(data, function(i, item) { console.log(item.message); }); }, 5000); } ); });

这是我当前的JS代码:

$(function(){
$.getJSON("/get_slideshow_messages",
    function(data){
        setInterval(function(){
            $.each(data, function(i, item) {
                console.log(item.message);
            });
        }, 5000);
    }
);
});
我正在制作一个简单的幻灯片,对url的调用将返回一个Laravel雄辩的对象,形式如下:

return SlideshowMessages::all();
如果我将控制台日志记录为“数据”,则返回值为:

Object, Object, Object]
 0: 
     Objectcreated_at: null
     id: "1"
     message: "test1"
     updated_at: null
     __proto__: Object
 1: Object
 2: Object
  length: 3

如何正确循环数组,以便每次只接收一个项目?

您需要保留一个计数器,该计数器在每次调用间隔时都会更改,而不是使用each。我没有测试过这一点,因为我没有你的数据集-但理论上这应该是可行的

$(function(){
$.getJSON("/get_slideshow_messages",
    function(data){
        var currentSlide = 0;
        var nextSlide = function () {
                //Loop back around
                if (!data[currentSlide]) currentSlide = 0;
                console.log(data[currentSlide].message);

                //Increase our counter
                currentSlide++;
        }; 

        //render the first slide straight away
        nextSlide();

        //Set up our interval to render them every 5 seconds
        setInterval(nextSlide, 5000);
    }
);
});

使用$.each尝试的循环是否有任何问题?关闭–第一次只需立即调用该函数,否则当页面加载时,它将在显示第一张幻灯片之前等待5秒钟。