0

我试图让我的 laravel 刀片在选中/取消选中复选框时切换布局,到目前为止没有可见的结果,我错过了什么?这是我的代码的相关部分。

index.blade.php

...    
@if ($tab == true)
<div style="background-color:green;height:100px;width:200px;">
    //for test porposes a div with diff color only
    some text
</div>
<input type="checkbox" name="layout" value="1" onclick="processForm()" checked>
@else
<div style="background-color:red;height:100px;width:200px;">
    some text
</div>
<input type="checkbox" name="layout" value="1" onclick="processForm()">
@endif

...

@endsection

@section('scripts')
<script type="text/javascript">
function processForm() { 
   $.ajax( {
        type: 'POST',
        url: 'articles/layout',
        data: { layout : $('input:checkbox:checked').val()},

        success: function(data) {
            $('#message').html(data);
        }
    } );
}
</script>
@stop

路线

Route::resource('articles','ArticleController');
Route::post('articles/layout', [
        'as' => 'articles.layout',
        'uses' => 'ArticleController@layout'
    ]);

最后控制器ArticleController.php

<?php
namespace Vanguard\Http\Controllers\Web;
use Illuminate\Http\Request;
use Vanguard\Http\Controllers\Controller;
use Vanguard\Article;

class ArticleController extends Controller
{
    public function index()
    {
        $articles = Article::latest()->paginate(10);
        $page_title = "hello world";
        $page_title_sml = "small hello world";
        if (!isset($tab)) {
            $tab = false;
        }

        return view('articles.index',compact('articles', 'page_title' , 'page_title_sml', 'tab'))
            ->with('i', (request()->input('page', 1) - 1) * 5);

    }

...

 //custom function
        public function layout(Request $request)
    {
        $tab = $request->layout;
        return redirect()->route('articles.index')
                        ->with('success','Layout changed');
    }
    //end custom function
}

我的逻辑是:Ajax 监视器复选框 > 一旦它被选中/取消选中,Ajax 将发布请求发送到文章/布局 > 触发 ArticleController@layout > 哪个进程复选框变量 > 重定向到控制器的文章索引 > 以相应地显示刀片。

我错过了什么?有没有更好/更简单的方法来实现这一目标?谢谢

4

0 回答 0