Laravel:将div改为ajax和多个controller@action

Laravel: Change the div with ajax and multiple controller@action

我想用 AJAX 更改 div 的内容(我不想在单击链接时重新加载所有页面),我找到了一些文档,但是我只看到 "static" 解决方案(它们是 "hard coded" 和 "if you click on this bring this",但我不想在我的项目底部使用 3000 行开关盒)。

有人可以告诉我一个 "dynamic" 解决方案,我只需要将控制器、动作和参数提供给点击按钮,jquery 路由器就可以在不进行修改的情况下进行路由?

我的示例代码:

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
    <head>
        @include('includes.head')
    </head>
    <body>
        <div id="header">
         <nav id="navbar" class="navbar navbar-default">
           <ul class="nav nav-tabs navbar-right">
                <li>
                    <a action="FirstExampleController@firstExamle" params="[a => 24, b => 52]">
                        <button type="button" class="btn btn-link">First Example</button>
                    </a>
                </li>
                <li>
                    <a action="SecondExampleController@secondExamle" params="[id => 1, newValue => 42]">
                        <button type="button" class="btn btn-link">Second Example</button>
                    </a>
                </li>
         </nav>
        </div
        <div id="app">
            <!-- This will be changed by the router -->
        </div>
        <footer class="container navbar">
            @include('includes.footer')
        </footer>

        <!-- Scripts -->
        <script src="{{ asset('js/app.js') }}"></script>
    </body>
</html>

控制器操作

class FirstExampleController extends Controller{

    public function firstExample(Request $request){
        $a = $request -> a;
        $b = $request -> b;

        $c = $a + $b;

        return $c;
    }
}

class SecondExampleController extends Controller{

    public function secondExample(Request $request){
        $id = $request -> id;
        $newValue = $request -> newValue;

        //database operation where the id's object's new value will be $newValue

        return $this->showItems;
    }
}

这样做,

首先向每个 button 添加一个 id 以及 <a> 内的链接,您可以将其用作 ajax 的选择器并使用 [= params 的 15=] 属性您可以阅读有关数据属性的更多信息 here

 $('#buttonID').click(function(e) {  // e=event
        e.preventDefault();
        var param1 = $(this).data("param1")
        var param2 = $(this).data("param2")
        // so on....
        $.ajax({
           url: "/routeNames",
           type: "GET"/"POST",
           data: { data1: param1, data2: param2 }, 
           success: function(response) {
           console.log(response);  
    }
   });
});

注意: 您不需要像这样指定 SecondExampleController@secondExample 而是使用 routes 阅读更多关于 routes 的信息,只需指定路由名称或路由 URI。

PS:这只是一个基本结构。您需要进行研发才能充分利用它。