【问题标题】:PHP header redirect after ajax call does not have $_SESSION variables setajax 调用后的 PHP 标头重定向没有设置 $_SESSION 变量
【发布时间】:2014-06-14 19:19:53
【问题描述】:

我发现了一些获取浏览器窗口宽度和高度的 jquery 和 ajax 代码。我不知道 jquery 或 ajax,但我很高兴让它工作,有点。下面的脚本与需要运行的下一个脚本的链接完美配合。两个 $_SESSION 变量都已正确设置且可用。当我通过标头重定向链接到 score.php 时,显然没有设置 $_SESSION 变量,因为它们在 score.php 中为空。时间问题?

我真的不希望用户必须单击才能继续的链接。 (这些脚本是要求用户“登录”的系统的一部分。)是否有一个简单的解决方案可以重定向到 score.php 以便 browserWidth 和 browserHeight 值可用?我可以将它们作为 $_SESSION 变量或参数访问(score.php?w=$browserWidth&h= . . .)。

<?php   
session_start();  
?>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
</head>  
<body>  
<?php  
/******************************************* 
/ code from http://holden.pro/test/test2.php   
/******************************************/   
if(!isset($_POST['width']) || !isset($_POST['height'])) {  
  echo '  
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
  <script type="text/javascript">
  $(document).ready(function () {
    var height = $(window).height();
    var width = $(window).width();
    $.ajax({
      type: \'POST\',
      url: \'get_window_size.php\',
      data: {
        "height": height,
        "width": width
      },
      success: function (data) {
        $("body").html(data);
      },
    });
  });
  </script>
  ';
}

$_SESSION['browserWidth'] =  $_POST['width'];  
$_SESSION['browserHeight'] =  $_POST['height'];  

echo '<a  href="score_image.php">Score Image</a>';    // THIS WORKS!

/*  THIS DOES NOT WROK
$location = 'Location: score_image.php';  
header("$location");  
header("content-type: text/html; charset=utf-8");  
*/
?>  
</body>  
</html>

【问题讨论】:

    标签: javascript php jquery ajax redirect


    【解决方案1】:

    PHP Header - Manual

    <?php
    $width = $_POST['width'];
    $height = $_POST['height'];
    
    
    $host  = $_SERVER['HTTP_HOST'];
    $uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
    $extra = 'score_image.php?h='.$height.'&w='.$width;
    header('Location: http://'.$host.$uri.'/'.$extra);
    exit;
    ?> 
    

    【讨论】:

    • 您的标头肯定比我的要好,但是 score.php 中的高度和宽度仍然为空。我不认为问题出在标题上。相反,这似乎是一个时间问题。如果脚本通过链接暂停,则可以成功传递宽度和高度。如果宽度和高度分配紧跟在标题之后,就好像从未设置过一样。
    猜你喜欢
    • 2014-08-25
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-13
    • 1970-01-01
    相关资源
    最近更新 更多