【问题标题】:Getting PHP error when embedding Jquery/JavaScript嵌入 Jquery/JavaScript 时出现 PHP 错误
【发布时间】:2017-08-06 08:33:02
【问题描述】:

我实际上对 PHP 或 JQuery 并不是特别陌生。这使得这个错误更加陌生。考虑这两个代码示例。 (因为我在这篇文章中用了大约五分钟的时间将它们拼凑在一起,所以它们既简单又凌乱——但要说明问题。)

<?php
print<<<HERE
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1     /jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-  ui.min.js"></script>
</head>
<p>Error show</p>
<button id="targetbutton" style="height: 60px width: 100px">mouse in</button>
<script>
$("#targetbutton").mouseover(function() 
{$("p").css("color", "red")
});
</script>
HERE;
?>

<?php
print<<<HERE
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</head>
<p>Error show</p>
<button id="targetbutton" style="height: 60px width: 100px">mouse in</button>
<script>
/*
$("#targetbutton").mouseover(function() 
{$("p").css("color","red")
});
*/
</script>
HERE;
?>

这两个代码块都会产生这个错误: 解析错误:语法错误,意外的 '(',期望变量 (T_VARIABLE) 或第 11 行的 ... 中的 '$' (实际上第二个说...第 12 行 - 显然)

此代码有效:

<?php
print<<<HERE
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</head>
<p>Error show</p>
<button id="targetbutton" style="height: 60px width: 100px">mouse in</button>
<script>
$("#targetbutton").mouseover(function() {
$("p").css("color", "red")
});
</script>
HERE;
?>

正如我所提到的,我把这个有点混乱和简单化的例子放在一起来说明一个观点。但是,我首先在我正在创建的格式良好的网站中看到错误 - 因此代码美观 - 或缺乏这样的 - 似乎不是问题。)因此出现了三个问题: 1. 为什么 PHP 会抛出关于非 PHP 代码的错误(第 11 行在 script 标签内)? 2. 为什么 PHP 会抛出关于注释掉的代码的错误? 3.为什么大括号的移动突然解决了一切? 自从我开始工作以来,这个问题是认识论的,但很有趣。

【问题讨论】:

  • 这里没有什么奇怪的,它的工作原理与文档一致。阅读PHP Strings

标签: php jquery parse-error


【解决方案1】:

在 HEREDOC(和双引号字符串)中,{$ 引入了一个插值变量或表达式。

如果你想将内容转储到浏览器,要么完全退出 PHP 模式,要么使用 NOWDOC:

print <<<'HERE'
Note single-quotes around keyword
You can now have anything you like here and PHP won't try
to mess with it.
HERE;

【讨论】:

  • 哇... PHP 近 10 年了,从不知道 heredocs 中的 {$。谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-04-12
  • 2013-08-20
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
相关资源
最近更新 更多