views:

2341

answers:

2

For a very simple ajax name lookup, I'm sending an id from the client webpage to the server (Tomcat 5.5, Java 5), looking it up in a database and returning a string, which is assigned to a javascript variable back in the client (and then displayed).

The javascript code that receives the value is pretty standard:

//client code - javascript
xmlHttp.onreadystatechange=function() {
    if (xmlHttp.readyState==4) {
        var result = xmlHttp.responseText;
        alert(result);
        ...
    }
    ...
}

To return the string, I originally had this in the server:

//server code - java
myString = "...";
out.write(myString.getBytes("UTF-8"));

Which worked perfectly, if unsafe. Later, I replaced it with:

import org.apache.commons.lang.StringEscapeUtils;
...
myString = "...";
out.write(StringEscapeUtils.escapeJavaScript(myString).getBytes("UTF-8"));

But while safer, the resulting string can't be properly displayed if it contains special chars like "ñ".

For instance, using:

escapeJavaScript("años").getBytes("UTF-8");

sends:

an\u00F1os

to the client.

The question: is there a simple way to parse the resulting string in Javascript or is there an alternate escape function I can use in java that would prevent this issue?

+1  A: 

The following works in every browser I've tried:

javascript:alert("a\u00F1os");

Perhaps your string is being escaped twice by mistake.

Zorantula
Yes, I think in this particular case the escape was unnecessary (see my other comment below)
A: 

Actually, now that I read it over, I think I actually don't need to escape the string I'm sending back at all... That is, StringEscapeUtils.escapeJavaScript would be useful if the resulting value was printed in the page, like:

//javascript code with inline struts
var myJavasriptString = "<%=myJavaString%>";

Or am I missing something and there would still be a valid reason to do the escape in the original case? (when it is returned as a series of bytes back to an ajax onreadystatechange handler and assigned to a js variable)