4 回答

TA貢獻1943條經驗 獲得超7個贊
你可以做:
<!DOCTYPE html>
<html>
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
...
if($row) {
$myValue = 'Hi there!';
?>
<script>
var msg = "<?php echo $myValue; ?>"; //trying to set it to a JS var, so I could send it to below
//Your remaining js script here ...
</script>
<?php } else {
//your else condition
}
?>
</body>
</html>

TA貢獻1784條經驗 獲得超9個贊
嘗試這個
<!DOCTYPE html>
<html>
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
...
if($row) {
$myValue = 'Hi there!'
?>
<script>
var msg = "<?php $myValue; ?>";
</script>
<?php } else {
echo 'Incorrect Value';
}
?>
</body>
</html>

TA貢獻1876條經驗 獲得超7個贊
簡化你的代碼(調試時你應該總是這樣做?。┠阌羞@個:
$myValue = 'Hi there!';
echo <<<JS001
<script type="text/javascript">
var msg = {$myValue};
</script>
JS001;
如果您查看返回給瀏覽器的 HTML,您會發現它看起來像這樣:
<script type="text/javascript">
var msg = Hi there!;
</script>
瀏覽器不知道“你好!” 應該是一個字符串,所以它試圖將它作為代碼執行。
你想要的輸出是這樣的:
<script type="text/javascript">
var msg = 'Hi there!';
</script>
所以我們需要將這些引號添加到 PHP 中:
$myValue = 'Hi there!';
echo <<<JS001
<script type="text/javascript">
var msg = '{$myValue}';
</script>
JS001;
作為更通用的解決方案,您可以濫用 JSON 字符串是有效的 JS 值這一事實,并json_encode在 PHP 中使用:
$myValue = 'Hi there!';
$myValueJson = json_encode($myValue);
echo <<<JS001
<script type="text/javascript">
var msg = {$myValueJson};
</script>
JS001;
這在這種情況下沒有區別,但對于傳遞其他類型的值很有用 - 數組null等

TA貢獻1757條經驗 獲得超7個贊
為了更好地管理代碼,您可能應該將 HTML、PHP 和 JS 代碼分開放在不同的文件中。
想象一下這樣的事情:
控制器.php
$displayName="David";
include 'vue.php';
vue.php
<html>
...
<body>
<div id="php-data" data-displayName="<?php echo $displayName ?>"></div>
</body>
</html>
腳本.js
<script>
var msg = document.getElementById('php-data').dataset.displayName // "David";
</script>
添加回答
舉報