>我试图根据一个php变量设置要更改的图像的路径,该变量是通过读取window.innerWidth的cookie来确定的(在文件头部设置
)问题是浏览器在第一次渲染时没有正确读取cookie,我必须刷新浏览器x 2才能获得正确的图像。
有人可以指出我正确的方向吗? php 中是否有一种方法可以让 cookie 在第一次时始终正确读取 - 目前看起来它正在被缓存,或者类似的东西。
谢谢
这里的例子:http://markaprice.co.uk/2012dev/r-img-set/image-test-ht.php
下面的网页:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>document.cookie = "device_dimensions=" + window.innerWidth;</script>
<link rel="stylesheet" type="text/css" href="css/img-styles.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<title>Untitled Document</title>
</head>
<body>
<?php require_once('deliver-images.php'); ?>
<img class="ri" src="<?php echo $imgPath ?>the-landscape.jpg" alt="the landscape">
<img class="ri" src="<?php echo $imgPath ?>the-landscape-b.jpg" alt="the landscape">
PHP 脚本(交付图像.php)如下:
<?php
$device_width = 0;
$imgPath='';
// Read the device viewport dimensions
if (isset($_COOKIE['device_dimensions'])) {
$device_width = $_COOKIE['device_dimensions'];
echo($device_width);
}
if ($device_width > 0) {
// Low resolution image
if ($device_width <= 480) {
$imgPath = 'images/mobile/';
}
// Medium resolution image
else if ($device_width <= 1024 && $device_width > 480) {
$imgPath = 'images/tablet/';
}
else {
$imgPath = 'images/desktop/';
}
} else {
$imgPath = 'images/desktop/';
}
?>
你的以下行设置了cookie。
<script>document.cookie = "device_dimensions=" + window.innerWidth;</script>
这个php文件是你检查这个cookie的地方,以决定你要从哪个文件夹提供图像。
<?php require_once('deliver-images.php'); ?>
查看您的代码,您似乎正在这样想。
- 首先运行脚本标签并设置 cookie
- 然后你的PHP使用上一步中设置的cookie来做一些处理
但这是错误的,PHP首先在服务器上处理,然后将该页面发送到浏览器并运行脚本。
结论:第一次打开页面时,没有设置cookie,因为脚本将在php代码运行后运行。