Reputation: 820
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 javascript 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?
Upvotes: 0
Views: 1000
Reputation: 536595
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:
\
, '
, control characters and potentially Unicode characters, or just using a JSON encoder to do it for you.) Then,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.)
Upvotes: 3
Reputation: 887867
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.
Upvotes: 0