Need a little Javascript help!

{NcsO}ReichstaG

[H]ard|Gawd
Joined
Aug 13, 2004
Messages
1,768
Hello,
So I need to pass an array from PHP to javascript (nevermind the security risk). I did this using
Code:
implode(":#:",$array);
On the javascript side I used
Code:
split(":#:");
to turn it back into an array. However, when there is a character such as ' or "" " ', it doesn't work. How do I solve this? I tried encodeURI/decodeURI but it did not seem to work..
Also, do I call encodeURI after constructing the array?
-thanks
 
Instead of having javascript split a string to create an array, you could just echo code that creates the array.

Code:
<script>
<?php 
$test = array("'1\\'", '"2"', "'3'");
$str = "var test = new Array(";
for ( $i = 0; $i < count($test); ++$i ) {
    $str .= '"';
    $str .= str_replace( '"', '\\"', str_replace('\\','\\\\', $test[$i] ) );
    $str .= '"';
    if ( $i < count($test) - 1 ) {
        $str .= ", ";
    }
}
$str .= ");\n";
echo $str;?>
for ( var i = 0; i < test.length; ++i ) {
    alert( test[i] );
}
</script>

I don't know php methods well enough, so you'll have to clean that up, but that's the basic idea. Maybe addslashes will work better than the two replace functions.

Basically, that builds the string 'var test = new Array( "element1", "element2", element3" );'

If you do want to encode things and have js split it, then you can do it like this to get the same result.

Code:
<script>
<?php 
$test = array( "'1'\\", '"2"', "'3'" );
echo '    var test = decodeURIComponent("' . rawurlencode( implode( ":#:", $test ) ) . "\").split(\":#:\");\n";?>
    for ( var i = 0; i < test.length; ++i ) {
        alert( test[i]);
    }
</script>
 
Back
Top