tags:

views:

31

answers:

3

I am sticking values into a script, and I am using the function below to 'implode' the array

function implode() { var str='';
    for(item in globvars)
       str +='\n'+globvars[item]+';';
    return str+'\n';
}

Sample usage:

globvars = ['Tom', 'Dick', 'Harry'];
output = '<script type = "text/javascript">\n'+implode(globvars)+'</script\>';

Expected output should be:

    <script type = "text/javascript">
    Tom
    Dick
    Harry
    </script>

    Instead, I am getting something like this:

    <script type = "text/javascript">
    Tom Dick Harry </script>

what the ... ?

+1  A: 

It's working allright for me. Are you outputting the output to the browser? Browsers ignore newlines etc, do an alert(output) and you'll see that the newlines are there.

Also, your current initialization of globvars is wrong, you can't build an object like that. Use [ ] to build an array:

globvars = ['Tom', 'Dick', 'Harry'];
Tatu Ulmanen
Yeah, that was a typo. I am displaying in browser though
Stick it to THE MAN
+1  A: 

If you make your globvars as an array (see Tatu's answer), you can use the internal .join instead of implode:

globvars = ['Tom', 'Dick', 'Harry'];
output = '<script type = "text/javascript">\n'+ globvars.join(";\n") +';\n</script\>';
KennyTM
A: 

@Tatu Ulmanen

He is rendering a script tag. If he was doing <div>...</div> the \ns will get stripped out.

@OP

Try sending

<script><![CDATA[
    x
    y
    z
]]></script>

The ajax request might have munged it and stripped the newlines. If this was a straight-up rendering into a regular request the browser should not remove the \ns.

If this does not work please indicate:

What browser is being tested on, what kind of request is done, what you are trying to accomplish such that these newlines are so important.

Dmitriy Likhten