[英]Why won't this javascript work?
我拥有这段代码真让我感到沮丧:
<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>
由于某种原因,它只是无法正常工作。 请帮忙!
问题可能不在您的javascript代码中。
我的猜测是您有字符串转义问题。 在打印之前,尝试在$line
变量上使用addslashes
php函数。
// as simple as that
$line = addslashes($line);
因为如果一行中有引号,则您的PHP可以正常运行,但是您的JavaScript看起来像这样:
scriptAr.push("some text here "a quotation" and some other text");
这是无效的语法 。
如果使用addslashes
,则该行将变为:
scriptAr.push("some text here \"a quotation\" and some other text");
这将运行正常。
您不能“ write()”一个数组。 数组只是对象(在您的情况下是字符串)的集合。
您需要遍历它并依次打印每个元素:
for(var i in scriptAr) {
document.write(i + " => " + scriptAr[i] + "<br>\n");
}
所有这些操作是遍历每个元素并进行打印。 这些方括号用于索引(在这种情况下为变量“ i”),该索引用于处理各个元素。
print "scriptAr.push(\"$line\");\n";
如果$line
中的任何字符会混淆JavaScript字符串文字,例如"
, \\
, </script>
或换行符,这将引起问题。
document.write(scriptAr);
不好意思,因为您不能直接编写数组。 它将得到toString
修饰,这将在两行之间添加逗号的负载。
已经有一个很好的函数将PHP变量(包括数组)转换为JavaScript文字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>
尽管我不确定是否可以通过document.write()
传递一堆内容,而不是照原样输出,这有什么好处。 通常应避免document.write()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.