javascript - 将值从 PHP 传递到 JavaScript

标签 javascript php

我正在尝试打开一个新窗口,其内容来自 PHP 代码。我需要将值 $MsgWindow 传递给: JavaScript 中的 myWindow.document.write(something); 语句。 到目前为止我还没有成功做到这一点。 有什么建议么?

<!DOCTYPE html>
<html>
<?php>
     $info = array($_GET["airport"],
                   $_GET["state"],
                   $_GET["distance"],
                   $_GET["price"]);
    $fin=array();
    foreach ($info as $value) {
        $value = substr($value, 2);
        $value=substr($value, 0, -2);
        array_push($fin,$value);
    }
    $airport = $fin['0'];
    $state   = $fin['1'];
    $distance= $fin['2'];
    $price   = $fin['3'];
    $MsgWindow="Your estimate to ".$airport."  ".$state. " is ".$price;
    echo $MsgWindow;
    echo "<br>";
?>
<p>Click the button to write some text in the new window and the source (parent) window.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
   var myWindow = window.open("", "myWindow", "width=200, height=100");
    myWindow.document.write(something);
    myWindow.opener.document.write("<p>This is the source window!</p>");
}
</script>
</html>

最佳答案

您可以执行以下操作。该变量由 php 处理,并且显示为有效的 javascript 代码:

<script type="text/javascript">
   var php_var = "<?php echo $MsgWindow; ?>";
</script>

我想指出,如果 $MsgWindow 有引号,它将破坏脚本。您必须使用 addshlashes 来解决这个问题。

关于javascript - 将值从 PHP 传递到 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33269549/

相关文章:

javascript - 根据设备打开链接

javascript - 获取动态表值

php - 在 Symfony 2.8 中删除 "Remaining deprecation notices"

php - 如何在href中传递不同的信息

javascript - 如何在 AJAX 调用后使用新数据重新初始化tinyMCE?

javascript - 我如何使用 Vue.js 实现它?

javascript - 如何根据谷歌表格中其他单元格的值更改单元格的颜色

PHP:变量为空或未设置或什么?

php - 对于每个循环 PHP,插入 SQL 而不插入数据

php - 如何在不更改扩展名的情况下更改上传文件的名称