PHP内部的JavaScript无法正常工作

时间:2012-09-23 19:25:28

标签: php javascript html

<div class="interactionLinksDiv">
<a href="javascript:toggleReplyBox('.$fullname.','.$current_id.','.$current_id.','.$id.','.$thisRandNum.')">REPLY</a>
</div>

我用五个参数调用了javascript函数toggleReplyBox。这段代码写在php标签内。但是此代码未正确执行且参数未正确传递。如果我在这里调用函数toggleReplyBox没有参数它工作正常,但那不是我想要的。

<div class="interactionLinksDiv">
<a href="javascript:toggleReplyBox('<?php echo $fullname; ?>','<?php echo $current_id; ?>','<?php echo $current_id ; ?>','<?php echo $id; ?>','<?php echo $thisRandNum; ?>')">REPLY</a>
</div>

当我将此代码复制到我的php文件的html部分时它工作正常,参数传递并且函数正确执行。 但我想知道为什么当一切都相同时,函数无法在php标签内部工作。

function toggleReplyBox(sendername,senderid,recName,recID,replyWipit) {
$("#recipientShow").text(recName);
document.replyForm.pm_sender_name.value = sendername;
document.replyForm.pmWipit.value = replyWipit;
document.replyForm.pm_sender_id.value = senderid;
document.replyForm.pm_rec_name.value = recName;
document.replyForm.pm_rec_id.value = recID;
document.replyForm.replyBtn.value = "Send";
if ($('#replyBox').is(":hidden")) {
      $('#replyBox').fadeIn(1000);
} else {
      $('#replyBox').hide();
}      

}

在php标签内部,我更改了代码:

print <<<HTML
<div class="interactionLinksDiv">
<a href="javascript:toggleReplyBox('$fullname','$current_id','$current_id','$id','$thisRandNum')">REPLY</a>
</div>
HTML;

它仍然显示错误 解析错误:语法错误,第13行的C:\ xampp \ htdocs \ Fluid Solution \ fluid-solution-website-template \ interact \ profile1.php中的意外T_VARIABLE

第130行是<a href...行。

1 个答案:

答案 0 :(得分:4)

你的代码的第一个版本既不是PHP(javascript / HTML标签是“裸”)也不是Javascript:“。”字符串连接运算符在Javascript中不起作用,$variable扩展也不起作用。

你可以在PHP中使用它:

<?php
    $fullname = "Test";
    $current_id = 15;
    $id = 9;
    $thisRandNum = 42;
    // All lines beyond this point, and...
    print <<<HTML
<div class="interactionLinksDiv">
<a href="javascript:toggleReplyBox('$fullname','$current_id',
'$current_id','$id','$thisRandNum')">REPLY</a>
</div>
HTML;
    // ...up to here, start at the first column (i.e. they are not indented).
?>

请注意,在here-document(<<<HTMLHTML之间的区域)中,您不能使用字符串连接运算符“。” (或任何其他)。

或者您可以像在代码的第二个版本中那样执行操作,仅使用<?php echo $variablename; ?>替换变量,并将所有其余内容替换为HTML。

作为一个更简单的示例,让我们考虑一个带有PHP发送消息的alert()框。这意味着:

1)脚本在服务器端执行;执行<?php ?>个标记之间的任何内容,其输出会自行替换标记。

在此阶段之后,我们不再拥有PHP,而是HTML和Javascript的混合,可以由发送到的客户端执行。所以我们希望有一个类似

的HTML
<script type="text/javascript">
    alert('Hello, world');
</script>

为此,我们可以在PHP中生成所有HTML:

echo '<script type="text/javascript">';
echo "alert('$message');";  // or also:  echo 'alert("' . $message . '");';
echo '</script>';

或者我们可以使用here-document执行此操作,其中运算符不起作用,但$ variables执行:

echo <<<HEREDOCUMENT
<script type="text/javascript">
    alert('$message');
</script>
HEREDOCUMENT;

或者我们可以在HTML中运行它,并且只依靠PHP来生成单独的变量:

<script type="text/javascript">
    alert('<?php echo $message; ?>');
</script>

但是你总是需要分开在PHP中完成的工作,Javascript中的内容以及HTML标记中的内容。