laravel 怎么使用ajax

laravel 怎么使用ajax


一只萌萌小番薯
浏览 590回答 1
1回答

摇曳的蔷薇

laravel5刚好弄了一个,供参考。1.建议新手至少先弄通golaravel上入门的文章(一)和(二),否则理解比较困难<meta name="_token" content="{{ csrf_token() }}"/>2.前端js请求部分(注意那个header属性,是为了避免跨站伪造请求攻击写的)$.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方法上处理)Route::group(['prefix' => 'ajax', 'namespace' => 'Ajax'], function(){Route::post('create', 'PollController@store');});控制器方法PollController.php,<?php namespace App\Http\Controllers\Ajax;&nbsp;use App\Http\Requests;use App\Http\Controllers\Controller;&nbsp;use Illuminate\Http\Request;use Illuminate\Http\Response;use App\Poll;&nbsp; // 用数据模型&nbsp;use Redirect, Input, Auth, Log;&nbsp;class PollController extends Controller {public function store(Request $request){&nbsp; &nbsp; $poll = new Poll;&nbsp;&nbsp; &nbsp; $poll->date = Input::get('date');&nbsp;&nbsp; &nbsp; if ($poll->save()) {&nbsp; &nbsp; &nbsp; &nbsp; return response()->json(array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'status' => 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'msg' => 'ok',&nbsp; &nbsp; &nbsp; &nbsp; ));&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; return Redirect::back()->withInput()->withErrors('保存失败!');&nbsp; &nbsp; }}}
打开App,查看更多内容
随时随地看视频慕课网APP