你能给我建议吗?

我正在COOKIES中保存一些数据。我在Laravel中为此创建了一个方法,因此我在此方法上调用ajax来设置cookie,但是当我尝试在访问此cookie值的地方调用下一个请求时,它不会保存,并且可以在第二个请求中访问它...不知道为什么...这很奇怪:/

我有以下代码:

public function setCookie: method in laravel controller to set cookie
var setCookie: function in javascript where I call ajax request to set cookie
var loadEvents: method called after ajax call where I set cookie.


public function setCookie(Request $request) {

    $cookieName = $request->input('cookie_name');
    $cookieVal = $request->input('cookie_val');

    return response()->json(['status' => 'success'])->withCookie(cookie($cookieName, $cookieVal));
}


var setCookie = function (cookieName, cookieVal) {
    $.ajax({
        type: 'POST',
        url: window.setCookieUrl,
        data: {
            cookie_name: cookieName,
            cookie_val: cookieVal,
            _token: getCsrfToken()
        }
    }).done();
};



public function loadEvents(Request $request) {

    $activeCalendarsIds = $request->input('active_calendars_ids');
    if($activeCalendarsIds == null)
        $activeCalendarsIds = Cookie::get('adminActiveCalendars');


    $eventsPage = $this->getPostParam('page');
    $eventsLimit = $this->getPostParam('limit');

    $this->service->setFilter('page', $eventsPage);
    $this->service->setFilter('limit', $eventsLimit);

    $events = $this->service->getCalendarsEvents($activeCalendarsIds);
    $eventList = view('admin/calendar/event_list', ['events' => $events]);

    return response()->json([
        'status' => 'success',
        'data' => '' . $eventList . ''
    ]);

}

最佳答案

更新:以下功能可正常使用。似乎请求陈述的顺序有误。在发送任何loadEvent ajax请求之前,必须完成setCookie ajax请求。

Controller 操作:

public function set(Request $request)
{
    $cookieName = $request->input('cookie_name');
    $cookieVal = $request->input('cookie_val');
    return response()->json(['previousCookieValue' => Cookie::get('adminActiveCalendars')])->withCookie(cookie($cookieName, $cookieVal));
}

public function events() {
    return response()->json([
        'cookieValue' => Cookie::get('adminActiveCalendars'),
    ]);
}

Javascript / jQuery:
var setCookie = function(cookieName, cookieVal) {
  console.log('Set cookie', cookieName, cookieVal);
  $.ajax({
    type: 'POST',
    url: '{{ route('cookies.set') }}',
    data: {
      cookie_name: cookieName,
      cookie_val: cookieVal,
      _token: '{{ csrf_token() }}'
    },
    success: function(response) {
      console.log('Response:', response);
    }
  });
};

var loadEvents = function() {
  console.log('Load events');
  $.ajax({
    type: 'GET',
    url: '{{ route('cookies.events') }}',
    success: function(response) {
      console.log('Response:', response);
    }
  });
};

模板:
<button onclick="loadEvents();" type="button">Load Events</button>
<button onclick="setCookie('adminActiveCalendars', 'Foo');" type="button">Set Cookie Foo</button>
<button onclick="setCookie('adminActiveCalendars', 'Bar');" type="button">Set Cookie Bar</button>

控制台输出:
Load events
Object {cookieValue: null} // initially empty
Set cookie adminActiveCalendars Foo
Response: Object {previousCookieValue: null}
Load events
Response: Object {cookieValue: "Foo"} // first loadEvents request after setting cookie already holds correct value
Set cookie adminActiveCalendars Bar
Response: Object {previousCookieValue: "Foo"}
Load events
Response: Object {cookieValue: "Bar"}

完全重新加载页面后,然后加载事件:
Load events
Response: Object {cookieValue: "Bar"} // still here, right from the start

有关替代方法的说明:
  • 不知道应用程序的内部-似乎在客户端设置cookie就足够了
  • 如果客户端不需要其他信息,则可以将此类信息存储在Session变量中,而不是Cookie中。 There are some differences。首先,您不必费心在双方(客户端和服务器)上处理cookie。
  • 或者,不要在任何地方存储此信息-将其作为过滤器参数添加到请求中。


  • 原答案:

    这不会设置Cookie:
    return view('welcome')->withCookie(cookie($cookieName, $cookieVal, 45000));
    

    这样做:
    $response = new \Illuminate\Http\Response('Test');
    $response->withCookie(cookie($cookieName, $cookieVal, 45000));
    return $response;
    

    改编:
  • https://laravel.com/docs/master/requests#cookies
  • https://laracasts.com/discuss/channels/general-discussion/how-to-set-a-cookie-with-laravel-5
  • 09-10 10:15
    查看更多