Laravel:使用ajax和多个控制器@动作更改div

问题描述 投票:2回答:1

我想用div更改AJAX的内容(我不想在点击链接时重新加载所有页面),我发现了一些文档,但我只看到了“静态”解决方案(它们是“硬编码”的“如果你点击这个带来这个”,但我不想在我的项目底部使用3000行开关盒。

有人可以向我展示一个“动态”解决方案,我只需要将控制器,操作和参数提供给点击,而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;
    }
}
php ajax laravel laravel-5.5
1个回答
3
投票

这样做,

首先为每个id以及button内部的链接添加<a>,您可以将其用作ajax的选择器,并使用data-*属性params,您可以阅读有关数据属性的更多信息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:这只是一个基本结构。您需要进行研发以获得最佳效果。

© www.soinside.com 2019 - 2024. All rights reserved.