简体   繁体   中英

Why won't this javascript work?

It's been really frustrating me i have this code:

<script type ="text/javascript">
scriptAr = new Array(); // initializing the javascript array

<?php

foreach ($docsannlist as $subdocs) 
{
    $lines = $subdocs; // read file values as array in php
    $count = count($subdocs); //this gives the count of array
    //In the below lines we get the values of the php array one by one and update it in the script array.
    foreach ($lines as $line)
    {
        print "scriptAr.push(\"$line\");\n"; // This line updates the script array with new entry
    }
}

?>

document.write(scriptAr);
</script>

and for some reason its just not working. Please help!

The problem is probably not in your javascript code.

My guess is that you have string escaping problems. Try to use addslashes php function on the $line variable before printing.

// as simple as that
$line = addslashes($line);

Because if a line has a quote your PHP will work fine but your javascript will look like this:

scriptAr.push("some text here "a quotation" and some other text");

Which is invalid syntax .

If you use addslashes , the line will become:

scriptAr.push("some text here \"a quotation\" and some other text");​​

Which will run just fine.

You can't "write()" an array. An array is just a collection of objects (in your case, strings).

You'll need to loop through it and print each element in turn:

for(var i in scriptAr) { 
    document.write(i + " => " + scriptAr[i] + "<br>\n"); 
}

All this does is iterate over each element and print it. Those square brackets are for the index (the variable "i" in this case) which is used to address individual elements.

print "scriptAr.push(\"$line\");\n";

That's going to cause problems if there are any characters in $line that confuse a JavaScript string literal, such as " , \\ , </script> or a newline.

document.write(scriptAr);

That's dodgy, as you can't write an array directly. It'll get toString ​ified, which will add a load of commas in between the lines.

There's already a good function to turn PHP variables (including arrays) into JavaScript literals, json_encode :

<script type ="text/javascript">
    var docs= <?php echo json_encode($docsannlist, JSON_HEX_TAG); ?>;

    // Flatten docs list-of-list-of-lines into list-of-lines
    //
    var lines= [];
    for (var i= 0; i<docs.length; i++)
        lines= lines.concat(docs[i]);

    document.write(lines.join(''));
</script>

Although I'm not wholly sure what the advantage of passing a bunch of content through document.write() is, rather than just outputting it as-is. document.write() is generally to be avoided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM