-5

Possible Duplicate:
Parse a JavaScript file through PHP
PHP no longer working inside javascript

I am running .php files on my localhost and yesterday they worked and today they have errors, but I haven't changed the code. Here is a test file that has the same error as my longer actual code:

<html>
  <script type="text/javascript">
    <? $message = "Hello"; ?>
  </script>
  <? echo $message; ?>
</html>

I know this is a silly way to write Hello, but it demonstrates what error I am getting when I try to use php inside javascript. It was working perfectly fine yesterday and none of the code has changed. When I run this, it says "unexpected token <" on line 3. I think it is a problem with apache/php/mysql but I'm lost trying to fix it. Any suggestions would be great. Thanks.

4

3 回答 3

1

我猜,您禁用了短标签。您需要启用 PHP 短标签才能使其正常工作。检查这是否有效:

<html>
  <script type="text/javascript">
    <?php $message = "Hello"; ?>
  </script>
  <?php echo $message; ?>
</html>

在我看来,我不知道为什么要打开一个<script>标签并在那里声明一个 PHP 服务器端语句。你知道吗?它不输出任何东西。无论如何,上述代码的输出将是这样的:

<html>
  <script type="text/javascript">

  </script>
  Hello
</html>

所以没有必要拥有<script>标签,因为它是客户端,PHP 并不关心这一点。你可以在任何你想要的地方给出它,只要它们在<?php ?>标签内,它们就不会被浏览器解析。:)


如果您在自己的系统中执行此操作,要在 PHP 中启用短标签,请执行以下操作:

  1. 找到php.ini文件。
  2. 找到这个:

    short_open_tag = Off
    
  3. 将其更改为:

    short_open_tag = On
    

从手册:

short_open_tag:告诉 PHP 是否 应该允许 PHP 的 open 标记的缩写形式。(<? ?>)如果您想将 PHP 与 XML 结合使用,您可以禁用此选项以使用<?xml ?>内联。否则,您可以使用 PHP 打印它,例如:<?php echo '<?xml version="1.0"?>'; ?>. 此外,如果禁用,您必须使用 PHP open tag 的长格式(<?php ?>)

于 2013-01-31T17:24:53.577 回答
0

它不是有效的javascript。

运行 php 后,你最终会得到一个 dom,<script type="text/javascript"></script>因为你没有写任何东西。

尝试:

<script>
var hello = "<?php echo 'hello' ?>"
</script>
<script type="text/javascript">
document.writeln(hello)
</script>
于 2013-01-31T17:28:59.097 回答
-1

脚本对我来说很好用。您的问题中发布的代码是否完整?我能够重现该问题的唯一方法是使用以下代码:

<?php
<html>
  <script type="text/javascript">
    <? $message = "Hello"; ?>
  </script>
  <? echo $message; ?>
</html>
?>

如果我错了,请纠正我,但我假设您发布的代码在 *.php 文件中和 php 标签之间。如果是这种情况,请删除所述标签,它应该可以工作。

于 2013-01-31T17:30:10.503 回答