为什么不能在浏览器上阅读javascript与php设置的cookie?

时间:2013-04-17 11:22:32

标签: php javascript internet-explorer cookies opera

我有一个问题,我需要帮助。我正在做一些简单的步骤:

  1. 我用php设置了一个cookie(如果还没有设置)。
  2. 我用php再次读取这个cookie,它可以正常工作(对所有浏览器!)。
  3. 我这次用javascript重置了之前设置的cookie。
  4. 我读了javascript用php设置的cookie和firefox,chrome它工作正常,但在资源管理器,歌剧,safari(我使用最新版本)它不起作用。 cookie无法读取。没有错误返回,但cookie的字段是空白的。请参阅下面的代码。
  5. php代码:

    <?php
        if (isset($_COOKIE["parameters"])){
                $UserParam = json_decode($_COOKIE["parameters"],true);
                print_r($UserParam); // when the cookie is set by php it prints the array (on all browsers), but when cookie is set by javascript nothing print on explorer,opera,safari.
                echo"<script>function readCookie(){ alert(\"the cookie was there with radius: ".$UserParam['radius']." type: ".$UserParam['type']."\"); //again when the cookie set with php the variables have values on every browser, but when the cookie set with javascript no values to the variables.
                                getLocationFunction(\"".$UserParam["radius"]."\",\"".$UserParam["type"]."\",\"".$UserParam["date"]."\",\"".$UserParam["name"]."\")}</script>";
        }
        else { 
                $defaultParam = array("radius" => "ως 50km","type" => "all","date" => "unlimited", "name" => "all");
                $defaultParamSerialized = json_encode($defaultParam);
                setcookie("parameters","$defaultParamSerialized",time()+3600);
                echo"<script>function readCookie(){ alert(\"there was no cookie so i set it: radius ".$defaultParam["radius"]."\");
                                 getLocationFunction(\"".$defaultParam["radius"]."\",\"".$defaultParam["type"]."\",\"".$defaultParam["date"]."\",\"".$defaultParam["name"]."\")
                            }
                    </script>";
        }
    
    ?>
    

    javascript代码:

    function renewCookie(){ 
        var myArray = {radius: radius, type: type, date: price , name: company };
        var valueSerialized = JSON.stringify(myArray);
        createCookie('parameters',valueSerialized,999);   
      }
    function createCookie(name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
      }
    

    再次,我在所有情况下都使用php读取cookie,但是当我使用php创建它时,它可以被所有浏览器读取,当我使用javascript创建它时可以很好地阅读firefox,chrome但不在浏览器上,歌剧和野生动物园。

    note1:没有语法错误。

    note2:浏览器是最新版本。

    plz帮助。提前谢谢你!

1 个答案:

答案 0 :(得分:0)

试试,

更改此

if (isset($_COOKIE["parameters"])){

用这个

$COOKIE = isset($_COOKIE["parameters"]) ? $_COOKIE["parameters"] : "";

并在任何浏览器中使用print_r($_COOKIE)来查看差异。