简体   繁体   中英

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

I've found a php script to count my sites downloads. It saves downloads counts in a txt file as integer type. Like the count.txt contains only "109", means file was downloaded 109 times. I want to show the download counts using native javascript. Not PHP. just want to get the integer data from the txt file as variable. Is it posssible? if possible, how?

PHP Script is:

<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. Assuming the txt file is in the same directory as the file that runs the script, you should be able to use this code:

$(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.

I've used This JS for XmlHttpRequest to get the variable from 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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