将值从PHP传递到JavaScript

时间:2015-10-21 21:26:07

标签: 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>

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:1)

因为您正在构建javascript代码作为PHP脚本执行的一部分,所以您可以简单地在javscript片段中回显您要在其中使用它的PHP变量。

像这样:

<!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 type="text/javascript">
function myFunction()
{
   var myWindow = window.open("", "myWindow", "width=200, height=100");

       // Change here
       myWindow.document.write("<?php echo $MsgWindow; ?>");
       myWindow.opener.document.write("<p>This is the source window!</p>");
}
</script>
</html>