如何将变量从Javascript移动到PHP


How can I move a variable from Javascript to PHP?

这是我的代码。

<script>var test = window.location.hash.substr(1);      document.write(test);  </script>

这就是结果。access_token=CAAEfRaZBmZA7KHn26ZB1zaL2YUFUq5ZCN&amp;expires_in=7098

我只想在PHP会话变量中只包含"access_token=~~~~"这一部分。但当我搜索时,只有包含<script>var test = window.location.hash.substr(1); document.write(test); </script>这一部分的代码。

有办法吗?请帮帮我。我只想在这里包含"access_token=~~~"。

您根本不需要javascript,完全可以在PHP中完成。试试这个:

<?php
  session_start();
  if (isset($_GET['access_token']))
  {
    $_SESSION['access_token'] = $_GET['access_token'];
  }

您可以使用此方法,但只需进行一次狭缝修改,再加上ajax或在获得访问令牌后需要使用的方法

var QueryString = function () {//you may need to call this at a different time if the hash changes after page load
    // This function is anonymous, is executed immediately and 
    // the return value is assigned to QueryString!
    var query_string = {};
    var query = window.location.hash.substring(1);//**search was changed to hash
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
      var pair = vars[i].split("=");
      // If first entry with this name
      if (typeof query_string[pair[0]] === "undefined") {
        query_string[pair[0]] = pair[1];
      // If second entry with this name
      } else if (typeof query_string[pair[0]] === "string") {
        var arr = [ query_string[pair[0]], pair[1] ];
        query_string[pair[0]] = arr;
      // If third or later entry with this name
      } else {
        query_string[pair[0]].push(pair[1]);
      }
    } 
  return query_string;
} ();
//then access it with or whatever you want to do at this point.
if(typeof QueryString.access_token !== 'undefined'){
    //then use ajax to send the access_token as a POST variable
    $.ajax({
        type: "POST",
        url: url,
        data: {access_token: QueryString.access_token},
        ...
    });
}

然后使用PHP:

<?php
    session_start();
    if(isset($_POST['access_token'])){
        $_SESSION['token'] = $_POST['access_token'];
    }