开发者

String issue with Javascript adding dynamic HTML

开发者 https://www.devze.com 2023-03-12 10:40 出处:网络
I\'m using PHP to generate a Javascript button that adds in a checkbox and some other HTML. What is the proper way to escape these characters to include them in an onclick event?

I'm using PHP to generate a Javascript button that adds in a checkbox and some other HTML.

What is the proper way to escape these characters to include them in an onclick event?

I saw it suggested to convert ' and " to the ascii values, but that doesn't seem to have helped.

$tempOutput = "<a href='temp.txt'>\"Happy\"</a>";
$tempOutput = str_replace("'", "&#39;", $tempOutput);
$tempOutput = str_replace('"', "&quot;", $tempOutput);

just results in this if you echo the string right before use:

<a href=&#39;temp.txt&#39;>&quot;Happy&quot;</a>

and this if you inspect the page element:

<a onclick="
                    var divTag = document.createElement('div');
                    divTag.innerHTML = '&lt;a href='temp.txt'&gt;&quot;Happy&quot;&lt;/a&gt;';
                    document.getElementById('extraDiv').appendChild(divTag) ;
                ">test</a>开发者_如何学Go;

I've also tried just appending to the extradiv's innerHTML but no success there either.


I mostly use PHPs rawurlencode() and Javascript's unescape():

  <?php
    $tempOutput = '<a href="temp.txt">'.htmlentities('"Happy"').'</a>';
  ?>
  <a onclick="
              var divTag = document.createElement('div');
              divTag.innerHTML = unescape('<?php echo rawurlencode($tempOutput);?>');
              document.getElementById('extraDiv').appendChild(divTag) ;
             ">test</a>
  <div id="extraDiv"></div>

This will also avoid errors with other chars, e.g. linebreaks.


Escape like this

$tempOutput = str_replace(array("'",'"'), array("\'",'&quot;'), $tempOutput);


use html_entity_decode

0

精彩评论

暂无评论...
验证码 换一张
取 消