我正在尝试用ajax到laravel做一个帖子。使用get方法时,它可以正常工作,但使用POST时,它会失败。
这是代码: 在我的app.blade上,我已经把:
<meta name="csrf-token" content="{{ csrf_token() }}" />
在我的view.blade上,我有以下ajax代码:
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#employeeActivityTable').DataTable( {
ajax: {
url: "{!! route('ajaxactivityperemployee') !!}",
type: "POST"
},
columns: [
{ data: 'employee_id', name: 'employee_id' },
{ data: 'employee_name', name: 'employee_name' },
{ data: 'month', name: 'month' },
{ data: 'sum_task_hour', name: 'sum_task_hour' }
],
columnDefs: [
{
"targets": [ 0 ],
"visible": false,
"searchable": false
}
]
} );
...
我知道我的路线正在运行,因为我使用GET完成了所有工作并且工作正常而且我只将其更改为POST并且我使用了故障排除工具:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
这是我的路线:
//Employee activity
Route::get('employeeactivity', ['uses'=>'EmployeeActivityController@getView','as'=>'employeeactivity']);
//AJAX
//Activity per employee
Route::get('activityperemployee', ['uses'=>'Ajax\ActivityAjaxController@getActivityPerEmployee','as'=>'ajaxactivityperemployee']);
Route::get('activityperproject', ['uses'=>'Ajax\ActivityAjaxController@getActivityPerProject','as'=>'ajaxactivityperproject']);
Route::post('activityperemployee', ['uses'=>'Ajax\ActivityAjaxController@postActivityPerEmployee']);
这是ajax控制器:
public function getActivityPerEmployee()
{
$return = $this->activityRepository->getActivityPerEmployee();
$data = Datatables::of($return)->make(true);
return $data;
}
public function postActivityPerEmployee(Request $request)
{
$where = [['col'=>'employee_id','val'=>'13'],['col'=>'month','val'=>'Jan']];
$return = $this->activityRepository->getActivityPerEmployee($where);
$data = Datatables::of($return)->make(true);
return $data;
}
public function getActivityPerProject()
{
$return = $this->activityRepository->getActivityPerProject();
$data = Datatables::of($return)->make(true);
return $data;
}
同样,如果在ajax请求中,我将类型从POST更改为GET,一切正常。
答案 0 :(得分:2)
您正尝试将Post请求发送到Get Route。
{!! route('ajaxactivityperemployee') !!}"
相关路线是:
Route::get('activityperemployee', ['uses'=>'Ajax\ActivityAjaxController@getActivityPerEmployee','as'=>'ajaxactivityperemployee']);
所以在你的情况下你可以做这样的事情(给你的邮政路线命名):
Route::post('activityperemployee','uses'=>'Ajax\ActivityAjaxController@postActivityPerEmployee', 'as'=>'postajaxactivityperemployee']);
然后在你的ajax调用中使用你的新命名路由:
{!! route('postajaxactivityperemployee') !!}"
将调用postActivityPerEmployee
操作