laravel怎么使用ajax分页
1个回答
展开全部
laravel5刚好弄了一个,供参考。1.建议新手至少先弄通golaravel上入门的文章(一)和(二),否则理解比较困难
1
<meta name="_token" content="{{ csrf_token() }}"/>
2.前端js请求部分(注意那个header属性,是为了避免跨站伪造请求攻击写的)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$.ajax({
type: 'POST',
url: '/ajax/create',
data: { date : '2015-03-12'},
dataType: 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
success: function(data){
console.log(data.status);
},
error: function(xhr, type){
alert('Ajax error!')
}
});
3.路由部分route.php(ajax/create路由打到Controllers/Ajax/PollController.php的store方法上处理)
1
2
3
Route::group(['prefix' => 'ajax', 'namespace' => 'Ajax'], function(){
Route::post('create', 'PollController@store');
});
控制器方法PollController.php,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php namespace App\Http\Controllers\Ajax;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Poll; // 用数据模型
use Redirect, Input, Auth, Log;
class PollController extends Controller {
public function store(Request $request)
{
$poll = new Poll;
$poll->date = Input::get('date');
if ($poll->save()) {
return response()->json(array(
'status' => 1
'msg' => 'ok',
));
} else {
return Redirect::back()->withInput()->withErrors('保存失败!');
}
}
}
1
<meta name="_token" content="{{ csrf_token() }}"/>
2.前端js请求部分(注意那个header属性,是为了避免跨站伪造请求攻击写的)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$.ajax({
type: 'POST',
url: '/ajax/create',
data: { date : '2015-03-12'},
dataType: 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
success: function(data){
console.log(data.status);
},
error: function(xhr, type){
alert('Ajax error!')
}
});
3.路由部分route.php(ajax/create路由打到Controllers/Ajax/PollController.php的store方法上处理)
1
2
3
Route::group(['prefix' => 'ajax', 'namespace' => 'Ajax'], function(){
Route::post('create', 'PollController@store');
});
控制器方法PollController.php,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php namespace App\Http\Controllers\Ajax;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Poll; // 用数据模型
use Redirect, Input, Auth, Log;
class PollController extends Controller {
public function store(Request $request)
{
$poll = new Poll;
$poll->date = Input::get('date');
if ($poll->save()) {
return response()->json(array(
'status' => 1
'msg' => 'ok',
));
} else {
return Redirect::back()->withInput()->withErrors('保存失败!');
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询