【问题标题】:Can't get COOKIE value after clicking submit button, working only after second clicking单击提交按钮后无法获取COOKIE值,仅在第二次单击后才起作用
【发布时间】:2020-05-21 19:45:46
【问题描述】:

我在使用 cookie 时遇到问题,我有一个表单:

if( isset($_GET['my_number']) ) {
    $my_text = esc_attr($_GET['my_number']);
}
?>
    <form id="my-form" method="get">
        <input id="my_number" type="number" name="my_number" value="<?php echo $my_number; ?>" />
        <input type="submit" name="submit" value="search">
    </form>
<?php

我想获得用户在按下提交按钮后在输入中输入的值并通过 cookie 和 javascript 回显该值。我的javascript:

$(document).ready(function () {
  const cookieMin = $("#my_number").val();
  createCookie("my_number_cookie", cookieMin, "10");
});

function createCookie(name, value, days) {
  var expires;
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toGMTString();
  }
  else {
    expires = "";
  }
  document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}

并在我的 php 中添加:

echo $_COOKIE['my_number_cookie'];

我得到了这个值,但只有在第二次提交按钮刷新之后。 我发现了一些关于这方面的问题,但他们的例子对我来说太难理解了。

你能帮帮我吗?

【问题讨论】:

    标签: javascript php


    【解决方案1】:

    这是因为您在首次提交后添加 cookie 已经发生。 因此,只有在第二次提交后您才会收到它。

    为了实现你想要的,你应该拦截表单提交事件并在那个时间添加你的cookie(即在提交表单发送之前)。

    所以,这里是解决方案:

    //Replace that code
    $(document).ready(function () {
      const cookieMin = $("#my_number").val();
      createCookie("my_number_cookie", cookieMin, "10");
    });
    
    //With this:
    $(document).ready(function () {
        $("#my-form").submit(function() { //after form is submitted
          const cookieMin = $("#my_number").val(); //took input value
          createCookie("my_number_cookie", cookieMin, "10"); //create your cookie
          //after that form will proceed the submit process, but with cookie added
        });
    });
    

    【讨论】:

    • Cookie 由 Set-Cookie: 标头设置,因此您必须从主机接收新的 HTML 页面才能看到它出现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多