繁体   English   中英

使用php获取文本文件并将字符串发送到javascript

[英]get a text file using php and send the string to javascript

好的,我想做的是创建图像的javascript循环,但是首先我必须获取图像列表。 在javascript中,无法直接获取此文本文件... http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt,但可以在php中轻松完成,我目前使用php获取txt文件,但是javascript无法读取该变量。 如何使javascript能够读取此变量。 这就是我所拥有的...

<?php
$file = "http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt"; //Path to your *.txt file
$contents = file($file);
$string = implode($contents);
echo $string;
?>
<script type="text/javascript">
    function prnt() {
        var whatever = "<?= $string ?>";
        alert(whatever);
    }
</script>

您可以使用echo或print来编写PHP页面。

var whatever = "<?php echo $string; ?>";

但是,如果文件中有换行符,则需要将其删除。

让它更有趣:继续拆分字段并使用JSON编码。 它应该直接在javascript中读取,而无需在客户端上调用JSON.parse()。

<?php
$lines = file_get_contents('http://...');
$lines = explode("\n",trim($lines));
foreach ($lines as &$line) {
    $line = preg_split('/,? /',$line);
}
$js = json_encode($lines);
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <script type="text/javascript">
        var dar = <?php echo $js; ?>;
    </script>
</body>
</html>

如果您计划频繁运行此文件,尤其是要在某个地方的公共Web服务器上提供文件,则还应该考虑使用本地代理来缓存该文件的结果。 将文件本地存储为“ noaa_data.txt”,并在cron作业中有第二个脚本(12小时左右):

<?php 
file_put_contents("/var/www/noaa_data.txt",file_get_contents("http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt"));
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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