Cookie和模态发送报头顺序错误

cookie and modal error with order of header being sent

本文关键字:报头 顺序 错误 模态 Cookie      更新时间:2023-09-26

我使用JavaScript制作一个弹出窗口(模式),警告人们我们在我们的网站上使用cookie。有一个接受按钮,点击应该创建一个cookie,持续60天,防止模式显示,但当我点击按钮,我得到一个错误说我不能修改头,因为它已经发送。

模态JavaScript取自w3schools和works,但我的浏览器得到一个错误"不能设置属性'onclick'为null"

代码如下:

<?php
  $cookie_name = "V3-cookies";
  if(!isset($_COOKIE[$cookie_name])) {
    include $_SERVER["DOCUMENT_ROOT"] . "/etc/cookie.php";
  } else {}
?>

/etc/cookie.php:

  <form id="modal" method="post" action="">
        <div class="modalconent tabs">
            <fieldset>
            <span class="close">×</span>
              <h2 class="fs-title">Cookies</h2>
              <h3 class="fs-subtitle">We use cookies to improve your experience</h3>
                 <iframe style="width:100%; height:80px;" src="/etc/txt/cookies.php" ></iframe><br />
               <input type="submit" name="cookie" value="Accept" class="btn fr" style="width:20%;" />
            </fieldset>
        </div>
    </form>
    <?php
      if(isset($_POST['cookie'])){
        $cookie_name = "V3-cookies";
        $cookie_value = "V3-cookies";
        setcookie($cookie_name, $cookie_value, time() + (86400 * 60)); // 86400 = 1 day
      }else{}
    ?>
    
    
    <script>
    window.onload = function () {
        document.getElementById('button').onclick = function () {
            document.getElementById('modal').style.display = "none"
        };
    };
    
    
    
    
    
    // Get the modal
    var modal = document.getElementById('modal');
    
    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];
    
    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        modal.style.display = "none";
    }
    
    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
    </script>

属性'onlick'为null的JavaScript错误在这里(第二行)

   window.onload = function () {
        document.getElementById('button').onclick = function () {
            document.getElementById('modal').style.display = "none"
        };
    };

header php error .

所以总共有两个问题。

  1. 我怎么能修复php设置cookie按钮点击?
  2. 如何删除浏览器错误,其中onclick为空?(2. 其实并没有那么重要,只是我讨厌出现错误)

我通过添加另一个设置cookie的页面来解决这个问题。所以cookie.php中的<form>将是<form actio="/etc/set_cookie.php" method="post">, set_cookie.php我使用与之前相同的php脚本。

我把这个答案贴出来是想让大家将来知道。