Php 使用innerHTML将带撇号的格式化文本从javascript传递到html元素

Php 使用innerHTML将带撇号的格式化文本从javascript传递到html元素,php,javascript,html,Php,Javascript,Html,我有3个页面加载相同的幻灯片。我试图通过从javascript向html元素传递变量中的新内容来整合到一个页面。效果应该类似于ajax。传递的内容包括html标记。所有这些都很好,但是如果我在文本中包含撇号符号,它就失败了。我可以用锐利的符号来解决问题;但是我想用撇号。下面是标记和脚本的示例。firefox、chrome和ie9中的结果相同。没什么大不了的,但我想知道为什么失败了。有什么想法吗 <?php // Test of script passing content to <p

我有3个页面加载相同的幻灯片。我试图通过从javascript向html元素传递变量中的新内容来整合到一个页面。效果应该类似于ajax。传递的内容包括html标记。所有这些都很好,但是如果我在文本中包含撇号符号,它就失败了。我可以用锐利的符号来解决问题;但是我想用撇号。下面是标记和脚本的示例。firefox、chrome和ie9中的结果相同。没什么大不了的,但我想知道为什么失败了。有什么想法吗

<?php
// Test of script passing content to <p> element
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
    <head>
<script type="text/javascript">
function testSwap(text) {
    var text1=text;
    document.getElementById('test').innerHTML = text1;
}
</script>
</head><body>
<?php
$testtext="&lt;img style= &quot; float:left;margin:10px &quot; src= &quot;          http://www.w3schools.com/images/pulpit.jpg &quot; alt=&quot; Pulpit rock &quot; width=&quot;50&quot; height=&quot;60&quot; /&gt; &lt;span style=&quot;font-weight:bold;font-size:16px;text-decoration:underline&quot; &gt; Second Page Title &lt;/span&gt; : This page tells how we found our family&#180;s origins. This sample includes an image, a span element with styling, and a double line break. &lt;br /&gt;&lt;br /&gt; They all work. Unfortunately, the script fails if I include an apostrophe in this text so I use &#180; instead.&lt;br /&gt;&lt;br /&gt;Same result in firefox, chrome and ie9. Not a big deal, but I&#180;d like to understand why it fails. Any ideas?";


?>
<div><button type="button" onclick="testSwap('<?php echo $testtext; ?>')">Click Me!</button></div>

<p id='test'><span style='font-weight:bold;font-size:16px;text-decoration:underline'>My Main Page Title:</span>
The pages are in a genealogy site with our family&#39;s history. Main page introduces site and describes content<br /><br />Other two pages use same slide show of family pictures, but have more detailed info.<br /><br />Menu currently directs to a new page and reloads the slideshow. I plan to use javascript to avoid the reload if user has it enabled.<br /><br />This sample demonstrates the idea. Click on the button for second page.
</p>

</body></html>

函数测试交换(文本){
var text1=文本;
document.getElementById('test')。innerHTML=text1;
}

使用
htmlentities

onclick=“testSwap(“”)”
您的
$testtext
中有引号,对吗?如果是这样,
htmlentities
将把报价变成
'
(如果是双引号,则为
和#34;
),并且不会中断
测试交换
onclick


编辑:对不起,我完全改变了我的答案。改为使用
htmlentities
(以前是urlencode)。

在页面呈现为HTML之前,PHP标记将替换为标记内表达式的结果。因此,由于您的
位于单引号内,因此渲染后这些引号将出现问题


您可以在字符串中使用反斜杠对引号进行转义,以便在HTML中呈现引号时正确显示。

为什么在英文文本中使用Ascii撇号(')或锐('),而不是使用正确的英文标点符号撇号(')?除了是正确的角色外,它还让你不必逃避它。您只需要正确处理字符编码,在任何情况下都应该这样做。
onclick="testSwap('<?php echo htmlentities($testtext); ?>')"