我有一个类似这样的php函数
function get_some_info()
{
$location = other_function_that_returns_a_string();
return <<<HTML
<script>
$("<h1> <?php echo $location ?> </h1>").insertAfter("header");
</script>
HTML;
}
但是我无法让我的变量动态显示。
我也尝试过类似的方法
$("<h1> <?php $location = other_function_that_returns_a_string() echo $location?> </h1>").insertAfter("header");
,它永远不会动态显示任何内容。如何显示我的变量?
答案 0 :(得分:2)
问题是您使用HEREDOC语法。
您不必在其中使用<?php
和?>
。
这可以正常工作:
$("<h1> $location </h1>").insertAfter("header");
这是我在PhpFiddle中测试的代码:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
Header
</header>
<?php
function other_function_that_returns_a_string(){
return "A string";
}
function get_some_info(){
$location = other_function_that_returns_a_string(); // Will be "A string"
return <<<HTML
<script>
$("<h1> $location </h1>").insertAfter("header");
</script>
HTML;
}
echo get_some_info();
?>