2017-08-06 84 views
-2

我對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

回答

0

在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。謝謝! –