在 echo <script> 内容中传递 PHP 变量
Pass PHP variable within echo <script> content
我正在尝试将 $php_variable 传递给 JavaScript 内容 在一个 php 文件 的 echo 标签中。这是因为我希望通过window.location
.
将查询值从old_page_url追加到new_page_url
例如,
http://example/?data=1234
到 http://example/something-else/1234
我的代码片段:
<?php
$php_variable = "testing";
echo "<script>";
echo "var toURL = 'http://example.com/something-else/'";
echo "window.location = toURL + $php_variable";
echo "</script>";
我试过:
<?php
$php_variable = "testing";
echo "<script>";
echo "var toURL = 'http://example.com/something-else/'";
echo "window.location = toURL + json_decode($php_variable)";
echo "</script>";
和
<?php
$php_variable = "testing";
echo "<script>";
echo "var toURL = 'http://example.com/something-else/'";
echo "window.location = toURL + <?php echo $php_variable; ?>";
echo "</script>";
但这两个都不行。有什么想法吗?
更新:最终代码片段
<?php
$php_variable = "testing";
$toURL = "http://example.com/something-else";
echo "<script>";
echo "window.location = '$toURL/$php_variable'";
echo "</script>";
这个怎么样
<?php
$php_variable = "testing";
echo "<script>";
echo "var toURL = 'http://example.com/something-else/'";
echo "window.location = toURL +" . "'{$php_variable}'";
echo "</script>";
echo "window.location = 'http://example.com/something-else/$php_variable'";
我正在尝试将 $php_variable 传递给 JavaScript 内容 在一个 php 文件 的 echo 标签中。这是因为我希望通过window.location
.
例如,
http://example/?data=1234
到 http://example/something-else/1234
我的代码片段:
<?php
$php_variable = "testing";
echo "<script>";
echo "var toURL = 'http://example.com/something-else/'";
echo "window.location = toURL + $php_variable";
echo "</script>";
我试过:
<?php
$php_variable = "testing";
echo "<script>";
echo "var toURL = 'http://example.com/something-else/'";
echo "window.location = toURL + json_decode($php_variable)";
echo "</script>";
和
<?php
$php_variable = "testing";
echo "<script>";
echo "var toURL = 'http://example.com/something-else/'";
echo "window.location = toURL + <?php echo $php_variable; ?>";
echo "</script>";
但这两个都不行。有什么想法吗?
更新:最终代码片段
<?php
$php_variable = "testing";
$toURL = "http://example.com/something-else";
echo "<script>";
echo "window.location = '$toURL/$php_variable'";
echo "</script>";
这个怎么样
<?php
$php_variable = "testing";
echo "<script>";
echo "var toURL = 'http://example.com/something-else/'";
echo "window.location = toURL +" . "'{$php_variable}'";
echo "</script>";
echo "window.location = 'http://example.com/something-else/$php_variable'";