【问题标题】:PHP URL Variable into JavascriptPHP URL 变量转换为 Javascript
【发布时间】:2016-02-12 11:11:41
【问题描述】:

在发现为什么我的网站没有通过 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;
   } // ?
?>

对初学者有什么想法/提示吗?

【问题讨论】:

  • 您需要将 php 变量回显到 javascript 中。 document.location.href='&lt;?php echo $url_endpoint;?&gt;';

标签: javascript php html variables url


【解决方案1】:

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

您只需要记住,当您使用 ?&gt; 关闭 PHP 时,PHP 变量将无法再访问,直到您再次使用 &lt;? 打开 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;
    }
?>

【讨论】:

  • 这只是代码的一部分,我忘记更正了。无论如何,感谢您对这个愚蠢问题的帮助。
  • 很好:)。我们都从某个地方开始
【解决方案2】:

使用类似的东西

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

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

【讨论】:

    【解决方案3】:

    用作

    <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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-12
      • 2016-01-10
      相关资源
      最近更新 更多