PDA

View Full Version : server side generated javascript advice



raphinou
4 May 2007, 6:28 AM
Hi,

I'm generating my javascript code on the server. Here's a situation where I'm looking for your advice:


profile_intro = new Ext.form.TextArea( {value: '<%=@profile.intro %>', fieldLabel: 'Intro'"} )


@profile.intro can include single and double quotes, but also new lines.

The code above could thus generate this:


profile_intro = new Ext.form.TextArea( {value: 'Hi there!

I hope you\'re doing fine.

Tell me what!
', fieldLabel: 'Intro'"} )


and give the error 'Unterminated string literal'.

What's the best solution to that problem? How are you solving it?

Thanks

Raph

jsakalos
4 May 2007, 6:37 AM
There were times when I also generated js by server. Now, when I have Ajax on hand I get ONLY data from the server.

This is much easier to maintain.

Animal
4 May 2007, 6:39 AM
You have to fix up the string so that it goes inside quote marks.

Here's some code I wrote years ago to do this:



/**
* Change quote and newline characters to their javascript character literal
* representations.
*/
public static String javascriptString(String in) {
StringBuffer result = null;
if (in == null) {
in = "";
} else {
result = new StringBuffer(in);
if (javascriptString(result)) {
return result.toString().trim();
}
}
return in;
}

/**
* Change quote and newline characters to their javascript character literal
* representations.
*/
public static boolean javascriptString(StringBuffer in) {
boolean result = false;
for (int q = in.indexOf("\"", 0); q != -1; q = in.indexOf("\"", q + 1)) {
// If the quote is not quoted with a backslash, change it to the
// javascript character literal
if ((q != 0) && (in.charAt(q - 1) == '\\')) {
in.insert(q++, "\\");
} else {
in.replace(q, q + 1, "\\u0022");
q += 5;
}
result = true;
}
for (int q = in.indexOf("'", 0); q != -1; q = in.indexOf("'", q + 1)) {
// If the apostrophe is not quoted with a backslash, change it to the
// javascript character literal
if ((q != 0) && (in.charAt(q - 1) == '\\')) {
in.insert(q++, "\\");
} else {
in.replace(q, q + 1, "\\u0027");
q += 5;
}
result = true;
}
for (int q = in.indexOf("\r", 0); q != -1; q = in.indexOf("\r", q + 1)) {
if (in.charAt(q + 1) == '\n') {
in.replace(q, ++q + 1, "\\n");
} else {
in.replace(q, ++q, "\\n");
}
result = true;
}
for (int q = in.indexOf("\n", 0); q != -1; q = in.indexOf("\n", q + 1)) {
in.replace(q, ++q, "\\n");
result = true;
}
return result;
}

raphinou
8 May 2007, 6:19 AM
I finally went another way:

I put the text in a hidden div and then


var text = Ext.get('hidden-div').dom.innerHTML;
new Ext.form.TextArea( { value: text})


This avoids an additional request to the server, and doesn't touch the text itself.