如何从课程中访问Cookie

时间:2018-08-03 06:04:34

标签: javascript php

我有一个脚本来获取正确或错误的值

var parent = document.getElementById('varför-välja-god-assistans');
var child1 = document.getElementById('cpm-id1');
var child2 = document.getElementById('cpm-id2');
var child3 = document.getElementById('cpm-id3');
if ( parent.contains( child1 ) ) {
var val1 = parent.contains( child1 );
document.cookie = "val1=1";
}
if ( parent.contains( child2 ) ) {
var val2 = parent.contains( child2 );
document.cookie = "val2=2";
}
if ( parent.contains( child3 ) ) {
var val3 = parent.contains( child3 );
document.cookie = "val3=3";
}

从php类中,如何访问val1,val2,val3的值

      $x1 =  $_COOKIE['val1'];
      $x2 =  $_COOKIE['val2'];
      $x3 =  $_COOKIE['val3'];

仅回显上面的值会给我一个错误(注意:未定义的索引:第137行的val1 inPopupwidget.php)

任何帮助将不胜感激(如果以上代码不正确,请提出更好的版本)

谢谢!!!

2 个答案:

答案 0 :(得分:0)

由于您有条件地执行了javascript中的代码块(如果有),因此可能未创建部分或全部cookie。因此,您应在尝试回显它们之前检查它们是否已设置。我建议像这样:

if (isset($_COOKIE['val1']) {
    $x1 = $_COOKIE['val1'];
    echo $x1;
}

或者对于不太冗长的内容,您可以使用双三元运算符:

$x1 = $_COOKIE['val1'] ?? null;

答案 1 :(得分:0)

<?php
print_r($_COOKIE);

?>
<script type="text/javascript">
//var parent = document.getElementById('varför-välja-god-assistans');
//var child1 = document.getElementById('cpm-id1');
//var child2 = document.getElementById('cpm-id2');
//var child3 = document.getElementById('cpm-id3');
//if ( parent.contains( child1 ) ) {
//var val1 = parent.contains( child1 );
document.cookie = "val1=1";
//}
//if ( parent.contains( child2 ) ) {
//var val2 = parent.contains( child2 );
document.cookie = "val2=2";
//}
//if ( parent.contains( child3 ) ) {
//var val3 = parent.contains( child3 );
document.cookie = "val3=3";
//}
</script>

结果:Array ( [val1] => 1 [val2] => 2 [val3] => 3 )

我认为您应该检查条件部分。