Ajax没有在laravel控制器中发布

时间:2018-05-24 20:38:33

标签: javascript php ajax laravel

<script type="text/javascript">
     $(document).ready(function(){
     $('#mainmenu').change(function(){
         var main_menu_id = $('#mainmenu').val();

         $.ajax({
             type: 'POST',
             url: '/sub',
             data: {"main_menu_id": main_menu_id,_token: '{{csrf_token()}}'
             success: function (data) {


var submenus = data.submenus;
      for(var i=0; i<submenus.length; i++){
      $('#submenu').append('<option>'+submenus[i]+'</option>');
    }   

          },
             error: function () {
                 alert('what ever');
             }
         }); 
     });
</script>

我的路线

Route::post('/sub','TicketController@sub');

我的控制器

public function sub(Request $request)
{    
    dd($request->all());
    return Response([
        'submenus' => DB::connection("mysql2")->table('applicationsubmenu')
        ->join('applicationmenu', 'applicationmenu.Id', '=', 
        'applicationsubmenu.ApplicationMenuId')
        ->select('applicationsubmenu.*')
        ->where('applicationmenu.MainMenuId', '=', $request->main_menu_id)
        ->get()->toarray(), 
    ]);
}

我正在尝试从用户选项菜单选择中填充一个选项子菜单。为此,我尝试构建一个ajax但它似乎根本不工作。laravel函数似乎根本就没有被调用!

4 个答案:

答案 0 :(得分:2)

尝试正确设置项目的ajax请求:

标题

.myList, .ofElements

在剧本中

<meta name="csrf-token" content="{{ csrf_token() }}" />

答案 1 :(得分:1)

为什么要将$request转储到控制器中?

 dd($request->all());

Laravel docs: dd函数转储给定变量,结束脚本执行 https://laravel.com/docs/5.6/helpers#method-dd

同样从$ request获取值时...您正在执行此操作:

->where('applicationmenu.MainMenuId', '=', $request->main_menu_id)

但你应该得到这样的值:

->where('applicationmenu.MainMenuId', '=', $request->input('main_menu_id')

或者如果你想要一个请求数组,那么你应该先设置:

$input = $request->all(); 

然后调用这样的值:

$input->main_menu_id

答案 2 :(得分:1)

您使用的是ajax中间件

吗?
Route::post('/sub','TicketController@sub')->middleware('ajax');;

答案 3 :(得分:0)

你忘了发送令牌

$holidays = array(
            '01-01',
            '01-06',
            '03-30',
            '04-01',
            '04-02',
            '05-01',
            '05-08',
            '07-05',
            '08-29',
            '09-01',
            '09-15',
            '11-01',
            '11-17',
            '12-24',
            '12-25',
            '12-26',
          );

// the starting date, $row['prijem'] in your example
$temp = strtotime("2016-03-25");

// add 30 days to the starting date
$plus30days = strtotime("+30 days", $temp);

// while the end date is a holiday or weekend, add another day
// do this check until the end date is _not_ a weekend or holiday
while(in_array(date("m-d", $plus30days), $holidays) || date('N', $plus30days) >= 6)
{
    $plus30days = strtotime("+1 day", $plus30days);
}

echo date("d.m.Y", $plus30days);