如何在Ajax Laravel 5.6中循环查看

时间:2018-07-26 02:48:17

标签: ajax laravel-5.6

说明:这里有一个按钮,当按下该按钮时将显示视图,可以看到问题,我在控制器中进行了循环。我不想在控制器中循环,但我想在view.blade.php中循环它,我该怎么做?

按钮:

<button onclick="getData('{{ $workbench->material_number }}','{{ $workbench->inc }}')"></button>

脚本AJAX:

function getData(argument, argument2) {
    $.ajaxSetup({
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
    });


    $.ajax({
        url: '{{ url("/workbench/manufacture_ref/detail") }}/'+argument+"/"+argument2,
        type: 'POST',
        data: {material_number: argument},
        success: function(str) {
            $("#manref_detail").html(str);
        }
    })

路线:

Route::post('/workbench/manufacture_ref/detail/{material_number}/{inc}', 'WorkbenchController@manref_detail');
enter code here

CONTROLLER:

public function manref_detail1($material_number) 
{
    if ( isset($_POST['material_number']) ) {

       $material_number = $_POST['material_number'];
       $i = DB::select("SELECT * FROM part_manufacture_ref WHERE material_number = '$material_number';");
       $token= md5(uniqid());

        foreach ($i as $value) {
            echo "<tr style='font-size: 12px' tabindex='0'>";
            echo "<th>$value->manufacture_code</th>";
            echo "<th>$value->source_type</th>";
            echo "<th>$value->manufacture_ref</th>";
            echo "<th>$value->type</th>";
            echo "<th>$value->note</th>";
            echo "</tr>";
           } 
    } else {
        echo "Access Denied";
    }
}

请帮助我,谢谢。

1 个答案:

答案 0 :(得分:0)

为什么不以JSON格式返回结果?

public function manref_detail1($material_number) 
{
    if ( isset($_POST['material_number']) ) {
        $material_number = $_POST['material_number'];
        $i = DB::select("SELECT * FROM part_manufacture_ref WHERE material_number = '$material_number';"); //Why dont you use Eloquent?
        $token= md5(uniqid()); //Why do you have this line? $token is not used?
        return $i;
    } else {
        echo "Access Denied";
    }
}

(也可以了解Laravel中的验证器,比if/else https://laravel.com/docs/5.6/validation容易得多)

然后您的View中就会有一个JSON响应。

因此,您可能会拥有一系列材料。

$.ajax({
    url: '{{ url("/workbench/manufacture_ref/detail")}}/'+argument+"/"+argument2,
    type: 'POST',
    data: {material_number: argument},
    success: function(result) {
        // So something with result. You can foreach here or call an external function.
    }
})