简体   繁体   English

PHP:代码变成HTML <! - 评论? - >

[英]PHP: Code gets turned into HTML <!— Comments? -->

when I enter in code like this: 当我输入这样的代码时:

<p>Hello <? echo $name; ?>, How are you?</p>

It prints: 它打印:

<p>Hello <!--? echo $name; ?-->, How are you?</p>

As a comment. 作为评论。 I have it in a file called base.js with this code: 我把它放在一个名为base.js的文件中,代码如下:

function showName() {
   document.getElementById("name").innerHTML = "<p>Hello <? echo $name; ?>, How are you?</p>";
}

So I embed the .js file like so: 所以我像这样嵌入.js文件:

<script type="text/javascript" src="base.js"></script>

So, after it changes the <p id="name"></p> I get: 所以,在它改变<p id="name"></p>我得到:

<p id="name">Hello <!--? echo $name; ?-->, How are you?</p>

I had the code in the .php file, and it seemed to work fine. 我在.php文件中有代码,它似乎工作正常。 Now that I have it in a separate base.js file, it ceases to function. 现在我将它放在一个单独的base.js文件中,它就不再起作用了。 Help! 救命!

That is because it is no longer php. 那是因为它不再是php。

Change to 改成

<script type="text/javascript" src="base.php"></script>

and have a 
<?php header("content-type:text/javascript"); 
$name = "...";
?>

function showName() {
   document.getElementById("name").innerHTML = "<p>Hello <?php echo $name; ?>, How are you?</p>";
}

Or 要么

change to 改成

function showName(name) {
   document.getElementById("name").innerHTML = "<p>Hello "+name+", How are you?</p>";
}

and in the php file have 并在PHP文件中

<script>
// using json_encode to make the string safe for script injection. 
// Still needs quotes for a single string
showName("<?php echo json_encode($name); ?>");
</script>

PHP is processed on the server side, not client side. PHP在服务器端处理,而不是在客户端处理。 You cannot execute PHP code on the client side. 您无法在客户端执行PHP代码。

Thist of all you cannot run php in the JS. 这一切都不能在JS中运行php。 The second is you have to do smth like this to avoid problem with comments: 第二个是你必须做这样的smth以避免评论问题:

//<![CDATA[
    function showName() {
       document.getElementById("name").innerHTML = "<p>Hello <? echo $name; ?>, How are you?</p>";
    }
//]]>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM