以上答案和其他资源一起帮助我制作了类似于“在 laravel 中使用 AJAX 设置会话”的示例。
我发布了一个简单的示例,其他用户可能会觉得这很有帮助。
查看 - ajax_session.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').on('click',function(){
// show that something is loading
$('#response').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: '/set_session',
data: $("#userform").serialize()
})
.done(function(data){
// show the response
$('#response').html(data);
})
.fail(function() {
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
});
</script>
</head>
<body>
<form id="userform">
{{ csrf_field() }} <!--required - otherwise post will fail-->
<input type="text" id="uname" name="uname" required/>
<button type='submit' id="submit">Submit</button>
<div id='response'></div>
</form>
</body>
</html>
routes.php
Route::get('session_form', function () {
return view('ajax_session');
});
Route::post('set_session', 'SessionController@createsession');
Route::get('allsession', 'SessionController@getsession');
控制器 - sessionController.php
public function createsession(Request $request)
{
\Session::put('uname', $request->uname);
echo "session created";
}
public function getsession()
{
dd(\Session::get('uname'));
}
您可以通过运行localhost:8000/session_form 进行检查。也可以通过localhost:8000/allsession单独查看会话。
希望对你有帮助!!!