[英]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.