简体   繁体   中英

What's the solution for this kind of problem?

<a onclick="run(&#039;Hi, Tim!  I&amp;#039;ve got two&#039;, &#039;">test</a>

The onclick event is not run at all.

The above is generated by something like this:

<a onclick="run(<?php echo htmlentities($str) ?>)">test</a>

How to fix it?

You are outputting the content of a string without quoting it

Put the echo statements in ''

<a onclick="run('<?php echo htmlentities($str) ?>')">test</a> 

By the way, &#039; = '

$str , before being entity-encoded, is:

'Hi, Tim!  I&#039;ve got two', '

which is clearly not a valid JavaScript string literal. The apostrophe is HTML-encoded, which it shouldn't be yet, and there's some trailing nonsense.

You should create JavaScript string (and other) literals using the json_encode function. If you have $rawstr as:

Hi, Tim!  I've got two

then json_encode will give you the correct JavaScript string:

'Hi, Tim!  I\'ve got two'

so you can insert it into an HTML event handler attribute:

<a onclick="run(<?php echo htmlspecialchars(json_encode($rawstr)) ?>); return false;">test</a>

Note htmlspecialchars() , which is preferable to htmlentities() , as the latter will usually-needlessly HTML-escape all non-ASCII characters, which will mess them up if you don't specify the correct charset.

From PHP 5.3, you can use the JSON_HEX_ flags to ensure that the HTML-special characters are never in the output from json_encode , which saves you an encoding step:

<a onclick="run(<?php echo json_encode($rawstr, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT) ?>); return false;">test</a>

To make your life easier, encapsulate these common output-with-escaping methods into more simply-named functions:

function h($s) {
    echo htmlspecialchars($s, ENT_QUOTES);
}
function j($s) {
    echo json_encode($s, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT|JSON_HEX_APOS);
}
function u($s) {
    echo urlencode($s);
}

<a onclick="run(<?php j($rawstr); ?>); return false;">test</a>

And even better, avoid using inline event handler attributes at all by binding from script:

<a id="test">test</a>
...
<script type="text/javascript">
    document.getElementById('test').onclick= function() {
        run(<?php j($rawstr); ?>);
        return false;
    };
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM