如何呈现PHP输出以初始化JavaScript中的变量?

时间:2014-08-10 12:14:43

标签: javascript php

我想在JavaScript代码中调用PHP函数来回显一个值:

<?php
function ex()
{
  $num=10;
  echo($num);
} 
echo '<script type="text/javascript">
  function sam_click(clicked)
  {
    var x="<?php ex(); ?>";
    alert(x);
    return false;
  }
</script>'?>

然而,它不起作用。你能帮忙吗?

6 个答案:

答案 0 :(得分:1)

试试这个:

<?php
function ex()
{
  $num=10;
  echo($num);
} 
echo '<script type="text/javascript">
  function sam_click(clicked)
  {
    var x="' . ex() . '>";
    alert(x);
    return false;
  }
</script>'?>

答案 1 :(得分:1)

试试:

...
var x="' . ex() . '";
...

答案 2 :(得分:1)

尝试仅回显您需要的内容

<?php
function ex()
{
  $num=10;
  echo($num);
} 
?>

<script type="text/javascript">
  function sam_click(clicked)
  {
    var x="<?php ex(); ?>";
    alert(x);
    return false;
  }
</script>

答案 3 :(得分:0)

function ex()
{
    $num=10;
    echo $num;
    return $num; // if you want to get JS alert
}
echo '<script type="text/javascript">
function sam_click(clicked)
{
    var x='.ex().';
    alert(x);
    return false;
}
sam_click(); // if you want to get JS alert
</script>';

答案 4 :(得分:0)

而不是回显$ num,将其作为结果返回,然后将其附加到脚本部分。

<?php
function ex()
{
  $num=10;
  return ($num);
} 
echo '<script type="text/javascript">
  function sam_click(clicked)
  {
    var x="' . ex() . '";
    alert(x);
    return false;
  }
</script>'?>

答案 5 :(得分:0)

heredoc和nowdoc的另一个解决方案:

<?php

// helper to call functions as nowdoc
// example: {$fn( function() )}
function fn($functionCall) 
{
  return $functionCall;
}
$fn = 'fn';

function ex()
{
  return 20;
}

$js = <<<EOT
<script type="text/javascript">
  function sam_click(clicked)
  {
    var x="{$fn(ex())}";
    alert(x);
    return false;
  }
</script>
EOT;

echo $js;

详细了解PHPDoc: