如何在 php 中回显 javascript 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16031719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to echo javascript code in php
提问by Daanvn
I am having a problem with how to echo javascript in php. I have a form which on submit will execute itself and echo some text and will redirect to a page in 5secs. I am currently echoing this:
我在如何在 php 中回显 javascript 时遇到问题。我有一个表单,它在提交时会自行执行并回显一些文本,并将在 5 秒内重定向到一个页面。我目前正在回应这一点:
header("Refresh: 5;url=index2.php?ID=".$objResult["ID"]."");
echo '<html>';
echo '<head>';
echo '<title>Klant toevoegen</title>';
echo '<link rel="stylesheet" href="style.css" type="text/css" media="screen" />';
echo '</head>';
echo '<body>';
echo '<fieldset>';
echo ''.$Naam.' is added to the database, u will be redirected in a couple of seconds.<br><br>';
echo '</fieldset>';
echo '</body>';
echo '</html>';
The javascript I have is a countdown which counts down from 5 to 1. The code is this:
我拥有的 javascript 是一个从 5 倒数到 1 的倒计时。代码是这样的:
<script>
var countdownFrom = 5; // number of seconds
var countdownwin;
var stp;
function CountDownStart() {
stp = setInterval("CountDownTimer('CountDownTime')",1000)
}
function CountDownTimer(id)
{
if (countdownFrom==0) {clearInterval(stp); window.close(); }
else {
var x
var cntText = "Closing in "+countdownFrom+" seconds";
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = cntText; }
else if (document.all)
{
x = document.all[id];
x.innerHTML = cntText; }
}
countdownFrom--
}
</script>
<title>Untitled</title>
</head>
<body onload="CountDownStart()">
<Div id="CountDownTime"></div>
</body>
Now I would like to echo this countdown script to replace the <fieldset>
in the html. I have tried several things like just add the whole code in 1 echo '';
and I tried to echo all the lines seperately but with both it crashes my whole script. If anyone knows how to do this it would be great!
现在我想回显这个倒计时脚本来替换<fieldset>
html 中的 。我尝试了几种方法,例如将整个代码添加到 1 中,echo '';
并且我尝试单独回显所有行,但是这两者都会使我的整个脚本崩溃。如果有人知道如何做到这一点,那就太好了!
回答by ilyail3
I Wouldn't write all those echo's, instead, leave all the HTML and JS outside the PHP block
我不会写所有这些回声,而是将所有 HTML 和 JS 留在 PHP 块之外
<?php
some php code
?>
HTML AND JS
<?php
More php if required
?>
And use
并使用
<?=$Naam?>
To inject your values where required
在需要时注入您的值
Alternatively you should look into template engines
或者,您应该查看模板引擎
回答by Victor
Try to use
尝试使用
echo <<<EOT
/* some text here */
EOT;
回答by Firezilla12
You can put the script in a separate .js file and echo
the script tag:
您可以将脚本放在单独的 .js 文件和echo
脚本标记中:
<? echo "<script type='text/javascript' src='path/to/script.js' ></script> ?>
Don't forget to remove any HTML tags from the JS file, like <body>
, <head>
, etc.
不要忘了从JS文件,就像删除任何HTML标签<body>
,<head>
等等。