Question

I am calling a javascript function in the onLoad of the body element in one of my webpages. Looks like this:

 <body onLoad="initPage(<%=object.getStringWithBrackets()%>); otherfunction();">

getStringWithBrackets() is a java function and will return a string like this: "['Name']"

When this happens a syntax error occurs: SyntaxError: syntax error initPage([

And there's a little arrow that points to after the bracket.

If I surround the scriplet with single quotes, the little arrow points inbetween the single quotes and bracket: initPage('[.

Are we not allowed to pass strings with brackets as parameters?

Edit: Thanks for the help so far. This is the line of html that is failing (I copied from the source after running into the error. I just changed names for the other function, everything else is untouched), I've put the single quotes back in around the scriplet to show the failure:

<body onLoad="initPage('["Print"]'); otherfunction('param1', 'param2', 'param3', 'param4', 'param5');">

Also wanted to mention that the java method getStringWithBrackets() is using Gson to return a json string version of java List(). That's how I get ["Print"].

Was it helpful?

Solution

It looks to me like your problem is that you're returning literally "['Name']" and you interpolate into an onLoad value that is itself wrapped in single quotes. I can't trace exactly why you'd end up with precisely what you're saying you're getting, but I'm guessing you didn't supply us your exact javascript code and that the onLoad is wrapped in the same quotation as the Name ( here you show single quotes where the string is being terminated ). So you end up writing out html that looks like this:

The onload becomes "initPage([" ( from your error I'm seeing the onLoad setting is terminated after the [ so it must have the same quotation as the onLoad string itself) and that of course, is not valid javascript.

You can of course pass strings with parameters as javascript. You can also pass arrays as parameters. But you cannot write both ' and " into a javascript expression which is itself enquoted with either one, unless you escape it.

Hope it helps!

OTHER TIPS

It looks like you need to add the quotes around the string value. Your asp.net code will return a string, but you need to have quotes around it to be treated as a string in javascript:

<body onLoad="initPage('<%=object.getStringWithBrackets()%>'); otherfunction();">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top