0

同じスライドショーをロードする 3 つのページがあります。javascript から html 要素に変数で新しいコンテンツを渡すことにより、1 つのページに統合しようとしています。効果は 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>
4

2 に答える 2

2

使用htmlentities: http: //php.net/manual/en/function.htmlentities.php

onclick="testSwap('<?php echo htmlentities($testtext); ?>')"

あなた$testtextはその中に引用が含まれているものですよね?もしそうならhtmlentities、引用符を&#039;(または二重引用符の場合)に変換し、 onclick&#34;を壊すことはありません。testSwap

編集:申し訳ありませんが、私は私の答えを完全に変えています。代わりに使用してくださいhtmlentities(以前はurlencodeでした)。

于 2013-03-15T23:12:40.477 に答える
0

PHP タグは、ページが HTML としてレンダリングされる前に、タグ内の式の結果に置き換えられます。したがって、<?php echo $testtext; ?>単一引用符で囲まれているため、レンダリング後にそれらの引用符に問題が発生します。

文字列にバックスラッシュを使用して引用符をエスケープすると、HTML でレンダリングされたときに正しく表示されます。

于 2013-03-15T23:13:43.047 に答える