Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

javascript - 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:

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

So I embed the .js file like so:

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

So, after it changes the <p id="name"></p> I get:

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

I had the code in the .php file, and it seemed to work fine. Now that I have it in a separate base.js file, it ceases to function. Help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That is because it is no longer 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

<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...