首页 > 解决方案 > 使用 php 和 js 遍历所有行

问题描述

在一个按钮内单击我想遍历表的所有行,我的代码:

@foreach( $questions as $q)


<script>


    var js_array = [<?php echo '"'.implode('","', $q).'"' ?>];



    var nextQuestion = (function() {
        var questionArray = js_array;
        var i = 0;
        return function() {
            $('#results').html(questionArray[i%questionArray.length]);
            i++;
        }
    })();


</script>

情况下的控制器逻辑:

$questions = DB::table('questions')->orderBy(DB::raw('RAND()'))->get();


$questions= json_decode( json_encode($questions), true);

return view('test', ['questions' => $questions]);

问题是它只遍历最后一行而不是所有行,不明白为什么。

标签: javascriptphplaravel-5

解决方案


您必须在脚本中添加循环函数。在顶部,您似乎想要输出每个返回。

但回报必须迭代。

例如这里描述的循环https://www.w3schools.com/js/js_loop_for.asp

您正在做的是将 i 设置为 0,然后返回...并完成。但是你必须一遍又一遍地循环。


推荐阅读