嵌入Jquery/JavaScript时出现PHP错误

问题描述:

我对PHP或JQuery并不特别陌生。这使得这个错误更加陌生。考虑这两个代码示例。 (因为我在大约五分钟这个岗位一起砍死他们,他们是简单而杂乱 - 但是要一点。)嵌入Jquery/JavaScript时出现PHP错误

<?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行 - 很明显)

THI S码的工作原理:

<?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行是脚本标签内)? 2.为什么PHP抛出有关注释掉代码的错误? 3.为什么一个花括号的移动突然解决了一切? 由于我得到它的工作这个问题是认识论,但有趣的。

+0

没有什么奇怪的是,在这里,它的工作原理,因为它是记录。阅读[PHP字符串](http://php.net/manual/en/language.types.string.php)。 – axiac

在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; 
+0

哇...差不多10年的PHP,从来不知道{$里面有heredocs。谢谢! –