在页面之间保持选择值

时间:2016-08-04 16:21:26

标签: ajax laravel laravel-5 laravel-5.1

我有几条路线

Route::get('/route_one', 'IndexController@index');
Route::get('/route_two', 'IndexController@index');

它们调用相同的控制器函数,因为这些页面需要相同的数据数组。该功能如下

public function index()
{
    $user = Auth::user();
    if( $user ) {
        $fileData = $this->fillArrayWithFileNodes(new DirectoryIterator( public_path(). '/images'));
        $currentPath= Route::getFacadeRoot()->current()->uri();

        if(!empty($fileData)) {
            return view('index', compact('fileData', 'currentPath'));
        }
    } else {
        return view('auth.login');
    }
}

现在索引视图很简单,但确实有这部分

@if($currentPath == 'route_one')
    @include('layouts.searchbarRouteOne')
@endif
@if($currentPath == 'route_two')
    @include('layouts.searchbarRouteTwo')
@endif

因此,根据调用的路径,会显示不同的侧边栏。现在,侧边栏基本上包含一些选择输入,如下面的

<div class="col-lg-3">
    <div class="form-group">
        <label>Year</label>
        <select id="year" class="form-control">
            <option value=""></option>
            @foreach($fileData["route_one"] as $year => $products)
                <option value="{{ $year }}">{{ $year }}</option>
            @endforeach
        </select>
    </div>
</div>

两个侧边栏都有不同的选择。选择选项时,会进行ajax调用以显示图像。一切正常。

这是我的问题。我有一个到达route_one或route_two的链接。当单击链接时页面刷新,选择处于其默认状态。我想以某种方式做的是保持选择输入的最后状态。我不是将这些数据存储在一个可能存在问题的数据库中吗?

此外,route_two依赖于route_one中的select选项。因此,当选择route_two时,我需要传递route_ones选项。

实现目标的最佳途径是什么?

由于

1 个答案:

答案 0 :(得分:1)

想想你在这里想要完成的事情:记住旧的输入值

您可以在点击链接时发送表单并在控制器中刷新数据,或使用JavaScript将输入值保存到浏览器的存储空间。

使用纯JavaScript的简单示例

// Get all select-elements
var inputs = document.querySelectorAll('select');

// Loop through them
for (var i = 0; i < inputs.length; i++) {
    // Set the old input value
    inputs[i].value = localStorage.getItem(inputs[i].name);

    // Start listening changes
    inputs[i].addEventListener('change', store);
}

// The function to call when the value has changed
function store(event) {
    // Set the new value to the browser's storage
    localStorage.setItem(event.target.name, event.target.value);
}

在该示例中,您的表单元素必须具有唯一的name属性。当然可以使用例如id属性。

相关问题