PHP URL变量为Javascript

时间:2015-11-11 11:05:26

标签: javascript php html variables url

在发现为什么我的网站没有通过header命令重定向之后,我发现了另一个问题。问题是我想把一些变量放入url重定向,即在javascript中。这是我的代码的一部分:

<?php
    $cost = 200
    $name = 'Bill'
    $url_endpoint = 'https://example.com/item1='.$cost.'&n='.$name.'.html';
    if( !headers_sent() ) {
        header("Location: $url_endpoint");
    }
    else {
?>

    <script type="text/javascript">
        document.location.href="$url_endpoint";   //That's just example what I want
    </script>
    Redirecting to <a href="$url_endpoint">site.</a> //Same here

<?php
    }
    die();
    exit;
   } // ?
?>

有关初学者的任何想法/提示吗?

3 个答案:

答案 0 :(得分:1)

您的脚本只需稍微修改变量输出到Javascript中。

您只需要记住,当您使用?>关闭PHP时,在使用<?再次打开PHP之前,不再可以访问PHP变量

你还有一个太多的结束括号,最终可能导致PHP错误。

<?php
    $cost = 200
    $name = 'Bill'
    $url_endpoint = 'https://example.com/item1='.$cost.'&n='.$name.'.html';
    if( !headers_sent() ){
        header("Location: $url_endpoint");
    }else{
?>
    <script type="text/javascript">
        document.location.href="<?php echo $url_endpoint;?>";
    </script>
    Redirecting to <a href="<?php echo $url_endpoint;?>">site.</a>
<?php
    die();
    exit;
    }
?>

答案 1 :(得分:0)

使用类似的东西

<script type="text/javascript">
   document.location.href="<?php echo $url_endpoint; ?>";
</script>

当你想将变量回显到html或你的情况下javascript。但你可以在谷歌搜索的第一页找到这个,而不问一个问题......在询问之前搜索了很多。

答案 2 :(得分:0)

用作

<script type="text/javascript">
  document.location.href="<?php echo $url_endpoint"; ?>;   //That's just example what I want
  </script>
  Redirecting to <a href="<?php echo $url_endpoint"; ?>">site.</a>