[英]get a text file using php and send the string to javascript
Ok, what I am trying to do is make a javascript loop of images, but first I have to get a list of the images. 好的,我想做的是创建图像的javascript循环,但是首先我必须获取图像列表。 In javascript there is no way to directly grab this text file... http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt but it can be done eaisly in php, I am currently gettung the txt file using php, but the javascript cannot read the variable.
在javascript中,无法直接获取此文本文件... http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt,但可以在php中轻松完成,我目前使用php获取txt文件,但是javascript无法读取该变量。 How can I make javascript be able to read this variable.
如何使javascript能够读取此变量。 Here is what I have...
这就是我所拥有的...
<?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>
You can use echo or print to write to the page in PHP. 您可以使用echo或print来编写PHP页面。
var whatever = "<?php echo $string; ?>";
Although, if the file has line breaks in it, you will need to remove those. 但是,如果文件中有换行符,则需要将其删除。
Make it a bit more interesting: go ahead and split the fields and use JSON encoding. 让它更有趣:继续拆分字段并使用JSON编码。 It should read directly in javascript without needing to call JSON.parse() on the client.
它应该直接在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>
You should also consider using a local proxy to cache the results of that file if you plan to run this frequently and especially if you are going to serve it up on a public web server somewhere. 如果您计划频繁运行此文件,尤其是要在某个地方的公共Web服务器上提供文件,则还应该考虑使用本地代理来缓存该文件的结果。 Store the file locally as "noaa_data.txt" and have a second script on a cron job (12 hours or something):
将文件本地存储为“ 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.