我有一个php函数,它输出一个带有按钮(带有帖子)的表单,以下载上一页上表格的pdf。出于某种原因,如果我尝试使用双引号,我会得到奇怪的结果,但是字符串声明中的单引号工作正常(除非我尝试将黄油喂给 js innerhtml)。
这有效:
$form = '<form action="../php/pdf_and_die.php" method="POST" target="_blank">';
$form .= '<input type="hidden" name="table" value="'.$table.'">';
// more lines here
$form .= '<input type="hidden" name="page" value="portrait">';
$form .= '<input type="submit" value=" '.$button_name.' " class="button"></form>';
但这不会:
$form = "<form action='../php/pdf_and_die.php' method='POST' target='_blank'>";
$form .= "<input type='hidden' name='table' value='{$table}'>";
// more lines here
$form .= "<input type='submit' value='{$button_name} ' class='button'></form>";
当我尝试使用双引号执行第二种方式时,表格显示在按钮之前。 带双引号的屏幕截图
就 php 和 html 而言,单引号/双引号不应该基本相同,只要它们被一致地使用吗?(除非像"foo{$bar}"这样的字符串中的变量那样的差异)。
这不是问题,我只会使用 php 函数中字符串声明的工作单引号,除了在另一个页面上,我有一个带有 onclick 的下拉菜单和一个 js 函数,该函数根据用户选择的学术会话将这些按钮之一替换为另一个按钮,而 innerhtml 似乎不喜欢单引号(内部双引号)选项。 截图
在显示按钮的页面上:(为便于阅读而缩写)
<?php
foreach ($sessions as $session) {
// string of attendance table
$session_table = get_class_attn_table($course, $acad_year, $session);
// get_pdf_form_button returns a string
$attn_button = get_pdf_form_button($session_table);
// add the output html to the array as a string
$sessions_text[] = $attn_button;
}
?>
<script type="text/javascript">
function toggle_session() {
var x = "" + document.getElementById("session_select").value;
var session1_text = "<?php echo $sessions_text[0];?>";
var session2_text = "<?php echo $sessions_text[1];?>";
if (x == "1") {
document.getElementById("change_session").innerHTML = session1_text;
}
else if (x == "2") {
document.getElementById("change_session").innerHTML = session2_text;
}
}
</script>
<select id="session_select" onchange="toggle_session()">
<option selected value="">Select...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
我对php和js很陌生,所以也许我错过了一些简单的东西。
正如注释中所说,$table
变量中确实有一些引号,这弄乱了 HTML。
有问题的报价的解决方案:
- 使用 PHP 内置函数
addslashes(string)
。 - 将双引号 (
"
) 替换为 HTML 字符实体"
,将单引号 ('
) 替换为 HTML 字符实体'
。字符实体引用图表 - 去掉引号。