Aya*_*hah 2 php ajax laravel laravel-5
我正在尝试访问 ajax 请求中的 laravel flash 消息。我搜索了一些可用的解决方案,但我想在不重新加载页面的情况下显示它们。
我在尝试什么:
在我的控制器中,我正在设置 flash 消息
Session::flash('success', 'Record has been inserted successfully');
Run Code Online (Sandbox Code Playgroud)
和
return response()->json([
'success' => 'ok' // for status 200
]);
Run Code Online (Sandbox Code Playgroud)
在阿贾克斯
success: function(data){
if(data.success){
// reload the current page
window.location.href = 'http://localhost/Framework/augLaravel3/public/index.php/user/add';
}
}
Run Code Online (Sandbox Code Playgroud)
在视图中
@if (Session::has("success"))
{{ Session::get("success") }}
@endif
Run Code Online (Sandbox Code Playgroud)
上面的代码工作正常,我只想删除重新加载步骤,因为我认为如果我通过ajax显示消息(不重新加载页面),对于复杂或大型应用程序会更方便。但是由于我是 laravel 的新手,所以我不知道我可以转换session::flash为 json 吗?
任何人都可以指导我,这可能吗?如果我们session::flash在ajax中访问它会是正确的方式吗?如果有人指导我,我将不胜感激。谢谢你。
不是像@Abbbas khan 建议的那样使用服务器的响应对 html 进行硬编码,我宁愿为 flash 消息返回一个子视图,并有可能在任何页面上重用该子视图。
1. 创建您的 flash 消息子视图: 创建 partials/flash-messages.blade.php
@if( Session::has("success") )
<div class="alert alert-success alert-block" role="alert">
<button class="close" data-dismiss="alert"></button>
{{ Session::get("success") }}
</div>
@endif
//Bonus: you can also use this subview for your error, warning, or info messages
@if( Session::has("error") )
<div class="alert alert-danger alert-block" role="alert">
<button class="close" data-dismiss="alert"></button>
{{ Session::get("error") }}
</div>
@endif
Run Code Online (Sandbox Code Playgroud)
2. 在你的控制器中: 定义你想要的成功信息并返回你的 flash-messages 子视图
use Session;
use View;
Session::flash('success', 'File has been uploaded successfully!');
return View::make('partials/flash-messages');
Run Code Online (Sandbox Code Playgroud)
3. 在您的主视图中: 在您希望 jquery 附加您的 flash 消息的位置放置一个空的 div
<div class="flash-message"></div>
Run Code Online (Sandbox Code Playgroud)
4.在您的ajax代码中: 将您的子视图作为html响应传递并将其附加到上面定义的div
$.ajax({
...
dataType: 'html', //Optional: type of data returned from server
success: function(data) {
$('div.flash-message').html(data);
},
...
});
Run Code Online (Sandbox Code Playgroud)
5. 为什么我喜欢这种方法: 使用这种服务器端方法,您可以在任何页面上重复使用您的 Flash 消息。您的 ajax 代码也得到了简化,您也可以简单地在另一个页面上再次使用它。您唯一需要自定义的是您在控制器中巧妙定义的消息内容!惊人的!
| 归档时间: |
|
| 查看次数: |
16581 次 |
| 最近记录: |