接口请求时设置客户端的cookie

本文介绍了一个关于使用Laravel框架通过AJAX设置Cookie的问题及解决方案。指出Cookie设置请求必须先于加载事件请求完成才能正确获取Cookie值。文章还讨论了不同实现方案的优劣。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


 

Update: the following works as expected. It seems there's a mixup in the order the requests are stated. The setCookie ajax request must be finished before any loadEvent ajax request is sent.

Controller actions:

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);
    }
  });
};

Template:

<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>

Console output:

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"}

After fully reloading the page, then loading events:

Load events
Response: Object {cookieValue: "Bar"} // still here, right from the start

Notes on alternative approaches:

  • Without knowing the internals of the application - it seems setting the cookie on the client side would be sufficient
  • Alternatively, store this kind of information in a Session variable rather than in a Cookie if it's not needed for something else on the client side. There are some differences. First of all you would not have to bother handling cookies on both sides (client and server).
  • Alternatively, do not store this information anywhere - add it to the request as filter parameters.

Original answer:

This doesn't set a cookie:

return view('welcome')->withCookie(cookie($cookieName, $cookieVal, 45000));

This does:

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


转至:http://stackoverflow.com/questions/35182197/laravel5-ajax-set-cookie-not-working
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值