Passing bad string as javascript parameter
I'm having a problem passing parameters that I think I should be able to solve elegantly (with 1 line of code) but I can't seem to solve the issue. I have a link to delete items, like so:
<a href="javascript:confirmDelete('${result.headline}',${result.id});">
The problem arises when result.headline contains characters like ' or " or others that break the javas开发者_开发技巧cript call. I have tried ${fn:replace(result.headline,"'","")}
which fixes issues for ' however I want to do some sort of URLEncode (I think) so that these characters dont break the javascript call. Any ideas on how to fix this without changing anything on the back-end?
Avoid putting inline JavaScript in elements, especially javascript:
pseudo-URLs which (apart from being Evil that should never be used) are JavaScript-in-URL-in-HTML. You would have to take the headline and:
- JavaScript string literal-encode it. (Replacing
\
,'
, control characters and potentially Unicode characters, or just using a JSON encoder to do it for you.) Then, - URL-encode it. Then,
- HTML-encode it.
Better to put the data in the markup where you only have to worry about simple HTML encoding in the way you do everywhere else to avoid cross-site-scripting:
<a href="#" class="confirmdelete-${fn:escapeXml(result.id)}" title="${fn:escapeXml(result.headline)}">Delete</a>
and have the JavaScript extract them:
<script type="text/javascript">
for (var i= document.links.length; i-->0;) {
var link= document.links[i];
if (link.className.indexOf('confirmdelete-')===0) {
link.onclick= function() {
confirmDelete(this.title, this.className.substring(14));
return false;
};
}
}
</script>
(there are potentially simpler, shorter or cleaner ways of writing the above using utility functions or frameworks, and there's an argument to be had over whether a link is really the right markup for this kind of action, but that's the basic idea.)
As long as you can rely on the fact that the strings don't have newlines, all you need to do is double all backslashes and escape all single quotes.
For example:
replace(replace(result.headline, "\\", "\\\\"), "'", "\\'")
This might not be valid syntax in your server-side language; I don't recognize it.
精彩评论