dsfhe34889 2011-09-07 07:21
浏览 23
已采纳

未生成Javascript Cookie

I am trying to implement this: http://adaptive-images.com/ into a website. It will rely on JS-Cookies that will get the screen's resolution so the PHP script that adapts the image sizes knows what resolution to deliver. Unfortunately it somehow fails to set the cookie (and falls back to 480 resolution...) and I have no idea why. What it does is simply:

<script type="text/javascript">
document.cookie='resolution='+Math.max(screen.width,screen.height)+'; expires=; path=/';
</script>

right in the head of the document. Yet, the cookie never seems to be set, I will only see (they should appear in the Resources Part of the Chrome DevTools, right?) the GoogleAnalytics-created ones (yet, this does not seem to be the problem as removing GA makes no difference).

I never used JS cookies before, but from what I can read on the web the syntax seems to be perfectly fine and also I do not get any kind of error messages in the console or elsewhere, it just seems to ignore the cookie setting action.

A long story short: I have no idea what's going on here?

Thanks!

EDIT: Maybe this is a PHP sided problem so I'll add this part too. What happens is the following:

First off:

$resolutions   = array(1920,1382, 992, 768, 480);

Then:

  if (is_numeric($_COOKIE['resolution'])) {
    $client_width = (int) $_COOKIE["resolution"]; 

    rsort($resolutions); 
    $resolution = $resolutions[0]; 

    foreach ($resolutions as $break_point) { 
      if ($client_width <= $break_point) {
        $resolution = $break_point;
      }
    }
  } 

Yet, the script will aways return a 480 resolution, even though my screen is 1920? As far as I get the code it should be returning 1920 so I guess it seems to use the fallback in case $_COOKIE['resolution'] is not set, which would be going back to 480.

  • 写回答

1条回答 默认 最新

  • dpp78272 2011-09-07 07:36
    关注

    Not setting an expires time makes your cookie a session cookie so it only lasts for the lifetime of the browser session (it is not written to disk).

    Other than that, your cookie seems to work for me. When I use that code in a jsFiddle and look in the Chrome debugger at the cookies, I see the cookie string with an item in it for resolution and it's marked as a session cookie, not a permanent cookie.

    Perhaps you can describe how you are reading the cookie?

    It occurs to me that you're setting the cookie on the client so the server will not see the cookie until the NEXT page requested on that domain. The server won't see it for the first page. Could this be your issue?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题