可以';t将PHP$var=file_get_contents(';path';)变量发送到javas


Can't send PHP $var=file_get_contents('path') variable to javascript function

这是我的javascript函数。

<script>
    function output($file_name, $content)
    {
     document.getElementById("content_title").innerHTML="    "+$file_name;
     document.getElementById("content").innerHTML=" "+$content; 
    }
</script>

这是我的PHP代码;

<?php
$dir = "img_png";
$files = scandir($dir);
$dir_length = count($files);
?>

这是我的PHP代码的第二部分(有问题);问题:当$content="任意字符串";一切正常,但当$content=file_get_contents('file');我的触发函数根本不会更改任何.innerHTML元素。

<?php
for ($i=2;$i<$dir_length;$i++){
$title=explode(".png", $files[$i]);
$content=file_get_contents('./content_txt/tv.txt');
echo "<td><button id='button' class='button' onClick='"output('", $title[0],"";
echo "', '", $content,"";
echo "')'"><img src='"/img_png/", $files[$i], "'"></img></button></td>";
}
?>

开始用这个解决问题(使用句点而不是逗号连接字符串)

<?php
for ($i=2;$i<$dir_length;$i++){
    $title=explode(".png", $files[$i]);
    $content=file_get_contents('./content_txt/tv.txt');
    echo "<td><button id='button' class='button' onClick='"output('" . $title[0];
    echo "', '" . $content;
    echo "')'"><img src='"/img_png/" . $files[$i] . "'"></img></button></td>";
}
?>

此外,我会在循环外设置$content-variable并跳过结束标记(这没有任何区别,因为没有使用</img>):

从php发送时也对数据进行编码(使用urlencode)

<?php
$content=file_get_contents('./content_txt/tv.txt');
for ($i=2;$i<$dir_length;$i++){
    $title=explode(".png", $files[$i]);
    echo "<td><button id='button' class='button' onClick='"output('" . $title[0];
    echo "', '" . urlencode($content);
    echo "')'"><img src='"/img_png/" . $files[$i] . "'"></button></td>";
}
?>

在您的javascript中,您必须解码内容:

function output($file_name, $content)
{
    $content = decodeURI($content);
    document.getElementById("content_title").innerHTML="    "+$file_name;
    document.getElementById("content").innerHTML=" "+$content; 
}

您的文件内容可能包含换行符或需要在JS中转义的特殊字符,在将字符串传递给javascript函数之前,您需要对特殊字符进行转义。

"tvvvvvv";

我想你把这个字符串从PHP复制粘贴到tv.txt

删除";-文件中不需要它。

"是javascript中的问题。