问题描述
我是PHP新手.我需要使用PHP输出以下JavaScript.这是我的代码:
I am new to PHP. I need to output the following JavaScript with PHP. This is my code:
<html>
<body>
<?php
echo "<script type="text/javascript">";
echo "document.write("Hello World!")";
echo "</script>";
?>
</body>
</html>
但是它显示了错误:
任何人都可以帮忙吗?我还需要一些有关如何在应用程序中使用PHP,HTML和JavaScript的简单教程.
Can anyone please help? I also need some simple tutorials on how to use PHP, HTML and JavaScript for an application.
推荐答案
您应该在PHP字符串中转义JavaScript字符串定界符.您正在使用PHP和JavaScript字符串的双引号.尝试像这样:
You should escape the JavaScript string delimiters inside the PHP string. You're using double quotes for both PHP and JavaScript strings. Try like this instead:
<html>
<body>
<?php
// Here, we use single quotes for PHP and double quotes for JavaScript
echo '<script type="text/javascript">';
echo 'document.write("Hello World!")';
echo '</script>';
?>
</body>
</html>
当字符串定界符与引号相同时,必须在JavaScript和PHP上都使用引号:
You have to escape quotes on both JavaScript and PHP when the string delimiter are the same as the quotes:
echo "\""; // escape is done using a backslash
echo '\'';
与JavaScript相同:
Same in JavaScript:
alert("\""); // escape is done using a backslash
alert(echo '\'');
但是由于很难读取具有此类转义序列的字符串,因此最好根据需要将单引号和双引号组合在一起:
But because it's very hard to read a string with such escape sequences, it is better to combine single with double quotes, as needed:
echo '"';
echo "'";
这篇关于如何使用PHP输出JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!