gpt4 book ai didi

javascript - 将 javascript 变量转换为 php 并使用 session 发送它

转载 作者:行者123 更新时间:2023-11-28 04:22:26 25 4
gpt4 key购买 nike

我想使用 session 发送文章 ID,源页面包含许多打开一个网页的链接,但 id 存在于 href 的 ID 属性中。就像

<br/>
< a id="13" class="openpage" href="test.html">open test form< /a><br />

我使用了javascript来传递变量

$(".openpage").on('click', function() {
var artid = $(this).attr("id");
<?php $_SESSION['artid'] = "<script>document.write(artid)</script>"?>
});


var artid 在加载新页面之前具有正确的值,而 $_SESSION['artid'] 未获取 artid 的值。

最佳答案

You'll have to update your index file and the test.html becomes test.php

jQuery part of the code takes the value of your ID attribute on the link Stores it in a cookie.

In your test.php The value of the COOKIE is assigned to your SESSION and the COOKIE is cleared using the in-built php set_cookie() function to set the cookie with an empty value (For security reasons);

cookie 将在1 分钟后过期。如果您愿意,可以更新它。

-

//index.php file

<a id="13" class="openpage" href="test.php" >open test form</a>

<!-- JS HERE --->

<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){

function setCookie(key, value) {
var expires = new Date();
expires.setTime(expires.getTime() + (60 * 1000));
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();

}

$(".openpage").on('click', function() {
var artid = $('.openpage').attr("id");
setCookie('cookie_session', artid);
});

});
</script>

//test.php file

 <?php
if(isset($_COOKIE['cookie_session'])):
$_SESSION['artid'] = $_COOKIE['cookie_session'];
setcookie("cookie_session", '');
echo $_SESSION['artid'];
endif;
?>

Here's a screenshot of the COOKIE in the browser's Dev tool > Application > Cookies

enter image description here

As you can see the COOKIE is no more in your browser and the SESSION now holds the data.

希望这有帮助:)

关于javascript - 将 javascript 变量转换为 php 并使用 session 发送它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45336326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com