[英]Can't get COOKIE value after clicking submit button, working only after second clicking
我有一個使用 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'];
我得到了這個值,但只有在第二次提交按鈕刷新之后。 我發現了一些關於此的問題,但他們的例子對我來說太難理解了。
你能幫我嗎?
發生這種情況是因為您在第一次提交后添加了 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
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.