laravel ajax提交登陆存储session,并输出
前端输出session
{{ Session::get('username') }}
ajax提交
<div>{{ Session::get('username') }}</div>
<meta name="csrf-token" content="{{ csrf_token() }}"> <!-- ajax提交必写验证 --> <script> $(function () { layui.use('form', function(){ var form = layui.form; // layer.msg('玩命卖萌中', function(){ // //关闭后的操作 // }); //监听提交 form.on('submit(login)', function(data){ // alert(888) $.ajax({ url: "/login", type: "POST", data:{"data":data.field}, headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, //ajax必写验证 jsonType:"json", success: function(e){ console.log(e); }, error:function(a){ console.log(a); } }); return false; }); }); }) </script> <!-- 底部结束 -->
控制器层
<?php namespace App\Http\Controllers; use App\Index; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class LoginController extends Controller{ public function index(){ return view('login'); } public function sub(Request $request){ //判断session指定项是否存在 if ($request->session()->has('username')) { echo "用户已登陆"; //获取session方法一 var_dump($request->session()->get('username')); //获取session方法二 //session('username'); //获取所有的session数据 // $request->session()->all(); //删除掉指定项的session; //$request->session()->forget('username'); //删除掉所有的session; //$request->session()->flush(); }else{ $data = $_REQUEST['data']; //把数据存储到session方法一 $request->session()->put('username',$data['username']); //把数据存储到session方法二 // session(['username' => $data['username']]); echo "未登录"; } } }