【问题标题】:Laravel strange issue with cookiesLaravel cookie 的奇怪问题
【发布时间】:2016-01-31 06:17:56
【问题描述】:

我试图在 cookie 存在时隐藏一条警报消息。

所以我有这个代码:

@foreach($alerts as $alert)
  @if(empty(Cookie::get('alert_'.$alert->id)))
    <!-- alert -->
    <div class="alert alert-{{ $alert->type }} text-center">
    <a href="#" onclick="createCookie('alert_{{ $alert->id }}','true','9999')" class="close" data-dismiss="alert" aria-label="close">&times;</a>
    {{ $alert->message }}
    </div>
  @endif
@endforeach

但是当 cookie 有一个值时,它仍然会被显示出来。

当我在代码中使用 isset() 时,我得到一个错误的连接重置。

我使用 javascript 来生成 cookie;

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

我做错了什么?

【问题讨论】:

    标签: javascript cookies laravel-4


    【解决方案1】:

    检查 cookie 是否存在

    试试这个:

    您还可以使用 request

    获取 cookie

    要检索 cookie 的值,请使用以下语法:

    $value = $request->cookie('nameOfCookie');
    

    如果需要,添加实例 Illuminate\Http\Request

    您可以如下检查cookie是否存在

    if (Request::hasCookie('alert_'.$alert->id)) 
    {
        // Success code here
    } else { 
        // Failure code here
    }
    

    你也可以同样检查:

    if(Cookie::get('alert_'.$alert->id) != null) { .. }
    

    有用的文档:hasCookie 方法。

    希望这有帮助。

    【讨论】:

    • 我都试过了......没有任何效果。提醒我在那之前我有一个 foreach 循环,也许是这样?
    • 我发现了问题,但无法解决。所以我说,当 cookie alert_[id] 存在时它需要隐藏,但当它不存在时,它需要显示警报。问题是,他显示了所有警报。所以现在我需要解决这个问题,但我不知道如何。
    • 你试过这个吗: if(!isset(Cookie::get('alert_'.$alert->id))) { // 显示 } else { // 隐藏 }
    • 是的,正如我在问题中所说,isses 阻止了我的连接。
    • 你能看到 foreach 循环中的每个 cookie 值吗?有空值吗?试试 strlen == 0 检查???
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 2013-12-24
    • 2019-07-27
    • 1970-01-01
    • 2020-06-27
    • 2020-01-29
    • 2020-05-13
    相关资源
    最近更新 更多