为什么Laravel的Session :: flash行为不一致? [英] Why is Laravel's Session::flash behaving inconsistently?
问题描述
在使用Laravel 4.2应用程序时,我最近注意到对Session::flash
(和类似的Input::flash
)的调用有时表现不一致.
While working on a Laravel 4.2 app, I have recently noticed that calls to Session::flash
(and similarly Input::flash
) sometimes behave inconsistently.
一个特定的例子:我想从edit
函数中刷新一些数据,以便可以在相应的update
函数中访问它. edit
视图包含一个相当简单的表单,包括一个字段,该字段在用户从下拉菜单中选择一个选项后通过AJAX调用加载.这是我的 MCVE :
One particular example: I want to flash some data from the edit
function so that I can access it in the corresponding update
function. The edit
view contains a fairly simple form, including one field that is loaded via an AJAX call after the user selects an option from a drop-down. Here is my MCVE:
在MyController.php
中:
<?php
class MyController {
public function edit($id) {
Session::flash('somevar', "myvalue");
return View::make('edit');
}
public function update($id) {
var_dump(Session::all()); die();
if (Session::has('somevar')) {
// do stuff
}
return Redirect::to('/');
}
}
?>
在AjaxController.php
中:
<?php
class AjaxController {
public function getinfo() {
return "here's that data you wanted";
}
}
?>
在edit.blade.php
中:
<script type="text/javascript">
$('form select[name=foo]').change(function() {
$.ajax({
url: '/ajax/getinfo'
success: function(data) {
alert(data);
}
});
});
</script>
<a href="/update/1">Update</a>
有时update()
中的会话转储将显示闪存数据,但有时会丢失.
Sometimes the session dump in update()
will show the flash data, but sometimes it is missing.
出了什么问题?
推荐答案
问题是需要额外的AJAX调用来填充其中一个字段.由于这算作一项请求,因此Flash数据对于该请求有效,但对下一个请求无效.
The issue is the extra AJAX call to populate one of the fields. Since this counts as a request, the flash data is active for that request, but not the next one.
为解决此问题,我在AJAX调用触发的函数的第一行中添加了Session::reflash()
,如下所示:
To fix this issue, I added Session::reflash()
to the first line of the function triggered by the AJAX call, like so:
<?php
class AjaxController {
public function getinfo() {
Session::reflash();
return "here's that data you wanted";
}
}
?>
这篇关于为什么Laravel的Session :: flash行为不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!