简体   繁体   English

如何使用JavaScript在会话中传递当前URL

[英]How to pass current url in the session using javascript

I have a button, I want when I click on it, current url passes on the session. 我有一个按钮,当我单击它时,当前URL会在会话中传递。 something like this: 像这样的东西:

$(".btn").click(function(e) {
     var url = window.location.href;
     // how to pass url in the session ?
});

Actually here is my structure: 实际上这是我的结构:

// pageA.php
<input class="btn" value="set current url to session" />

<script>
   $(".btn").click(function(e) {
     var url = window.location.href;
     // how to pass url in the session ?
  });
</script>


// pageB.php
if (isset($_SESSION['url'])){
    $previous_url = $_SESSION['url'];
    header('Location: $previous_url');
}

Now I want to know how can I pass a javascript variable in the php session? 现在我想知道如何在php会话中传递javascript变量? Or in other word, how can I set var url = window.location.href; 换句话说,如何设置var url = window.location.href; in the $_SESSION['url'] ? $_SESSION['url']

You can't do that directly because PHP is server-side and JavaScript is client-side and they simply can't "see" each other. 您不能直接做到这一点,因为PHPserver-sideJavaScriptclient-side ,它们根本无法相互“看到”。

You can eg. 您可以例如。 pass your variable (url) to PHP using Ajax (eg. jQuery.ajax() method) and then save it in your session like any other user data. 使用Ajax (例如jQuery.ajax()方法)将变量(url)传递给PHP ,然后像其他任何用户数据一样将其保存在会话中。

To send a Javascript value to PHP you'd need to use AJAX. 要将Javascript值发送到PHP,您需要使用AJAX。

JS : JS:

$(".btn").click(function(e) {
    var url = window.location.href;
    $.post('pageA.php', {url : url});
}

On your server, you would need to receive the url sent in the post like following : 在您的服务器上,您将需要接收帖子中发送的网址,如下所示:

PHP : PHP的:

$_SESSION['url'] = $_POST['url'];

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM