简体   繁体   English

如何从文本文件中获取整数数据作为Javascript变量?

[英]How to get integer data from a text file as a Javascript Variable?

I've found a php script to count my sites downloads. 我找到了一个PHP脚本来统计我的网站下载量。 It saves downloads counts in a txt file as integer type. 它将下载计数保存为整数类型的txt文件。 Like the count.txt contains only "109", means file was downloaded 109 times. 就像count.txt仅包含“ 109”一样,意味着文件已被下载109次。 I want to show the download counts using native javascript. 我想使用本机javascript显示下载计数。 Not PHP. 不是PHP。 just want to get the integer data from the txt file as variable. 只想从txt文件中获取整数数据作为变量。 Is it posssible? 有可能吗? if possible, how? 如果可能的话,怎么办?

PHP Script is: PHP脚本是:

<html>
<head>
<meta http-equiv="refresh" content="0;url=1.jpeg">
</head>
<body>

<?php

$fp = fopen("Count.txt", "r");
$count = fread($fp, 1024);
fclose($fp);
$count = $count + 1;
$fp = fopen("Count.txt", "w");
fwrite($fp, $count);
fclose($fp);

?> 

</body>
</html>

You can achieve this using AJAX. 您可以使用AJAX来实现。 Assuming the txt file is in the same directory as the file that runs the script, you should be able to use this code: 假设txt文件与运行脚本的文件位于同一目录中,那么您应该可以使用以下代码:

$(document).ready(function(){
        $.ajax({
            url: "Count.txt",
            success: function (dataString){
                console.log(dataString);
            }
        });
})

Note: This doesn't seem to work on localhost, but I tested it on my server and it worked. 注意:这似乎在localhost上不起作用,但是我在服务器上对其进行了测试,并且可以正常工作。

I've used This JS for XmlHttpRequest to get the variable from count.txt 我已经使用This JS for XmlHttpRequest从count.txt获取变量

<h1>Downloaded <span id="displaydlcount"></span> Times!

<script type="text/javascript">
     function lol(){
      var read = new XMLHttpRequest();
      read.open('GET', 'Count.txt', false);
      read.send();
      var displayName = parseInt(read.responseText)
      document.getElementById("displaydlcount").innerHTML = displayName;
      setTimeout("lol()",1000)
      }
      window.onload = lol();
</script>

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

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