Laravel5 AJAX设置cookie不起作用

时间:2016-02-03 16:17:42

标签: javascript php ajax cookies laravel-5

请你给我建议吗?

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

我有这段代码:

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 . ''
    ]);

}

2 个答案:

答案 0 :(得分:4)

更新:以下按预期方式工作。似乎请求的顺序混淆了。必须在发送任何loadEvent ajax请求之前完成setCookie ajax请求。

控制器操作:

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;

改编:

答案 1 :(得分:2)

问题是,如果我们想获取我们在前端设置的cookie,则会得到null作为值。但是,如果我们使用$ _COOKIE变量,我们可以访问它,这就是cookie存在的证明。那是什么问题?

默认情况下,该框架带来了用于加密cookie的中间件。如果我们从后端设置Cookie,则会对其进行自动加密,以便Laravel可以读取。在JS中,我们没有任何加密功能,这就是为什么我们无法从框架中访问它们。

在app / Http / Kernel.php的Web中间件组中,我们可以找到一个EncryptCookies :: class

在数组中,请设置您使用jquery或javascript设置的cookie名称

2:53am [login1] ~/JSHELL 1034:-)jshell jshell_prompt_file
|  Welcome to JShell -- Version 13.0.2
|  For an introduction type: /help intro

jshell> /set feedback genspice

GetNetConnectivity >