0

window.innerWidth (ファイルの先頭に設定されている) の Cookie を読み取ることによって決定される php 変数に従って、変更される画像のパスを設定しようとしています。

問題は、ブラウザによる最初のレンダリングで Cookie が正しく読み取られないことです。正しい画像を取得するには、ブラウザを 2 回更新する必要があります。

誰かが私を正しい方向に向けてもらえますか? Cookie を最初から常に正しく読み取る方法が php にありますか?現在のところ、キャッシュされているように見えます。

ありがとうございました

ここに例: http://markaprice.co.uk/2012dev/r-img-set/image-test-ht.php

以下のhtml:

<!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 スクリプト (deliver-images.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/';   
}





?>
4

1 に答える 1

0

あなたのこの次の行は、Cookie を設定します。

<script>document.cookie = "device_dimensions=" + window.innerWidth;</script>

そして、このphpファイルは、このCookieをチェックして、どのフォルダーから画像を提供するかを決定する場所です.

<?php require_once('deliver-images.php'); ?>

あなたのコードを見ると、そのように考えているようです。

  1. 最初にスクリプトタグが実行され、Cookie が設定されます
  2. そして、前のステップで設定されたそのCookieを使用して処理を行うPHP

しかし、それは間違っています。PHP は最初にサーバーで処理され、次にそのページがブラウザに送信され、スクリプトが実行されます。

結論 : 初めてページを開いたときは、php コードの実行後にスクリプトが実行されるため、Cookie は設定されていませんでした。

于 2012-05-25T10:58:49.810 に答える