简体   繁体   English

jQuery从.txt文件重新加载php值

[英]Jquery reload php value from .txt file

I want to reload some data from .txt files. 我想从.txt文件中重新加载一些数据。

The .txt files looks like this: 0;Player 1;10;Player 2;10;Player 3;0;Player 4;0;00:00:00;0;0 .txt文件如下所示:0;播放器1; 10;播放器2; 10;播放器3; 0;播放器4; 0; 00:00:00; 0; 0

I tryed to reload the data "10" after Player 1 which had the PHP Value $s1s[2] . 我试图在具有PHP值$s1s[2] Player 1之后重新加载数据"10"

Following Code does read the whole txt file (I know), but I am not familiar with Javascript and I need to get the output of this single Value instead of the whole txt file. 以下代码确实读取了整个txt文件(我知道),但是我对Javascript并不熟悉,我需要获取此单个Value的输出而不是整个txt文件。

PHP: PHP:

$spielfile = "data/$v/source.txt";

Javascript: 使用Javascript:

$(document).ready(function() {
  setInterval(function() {
    var randomnumber=Math.floor(Math.random()*100)
    $("<?php echo "#staende_$v" ?>").load("<?php print $spielfile ?>");
  }, 1000);
});

Any suggestion how I can do this? 有什么建议我该怎么做?

As Rory McCrossan mentions, you should be using an Ajax request returning data in JSON. 正如Rory McCrossan所述 ,您应该使用Ajax请求以JSON返回数据。

$(document).ready(function() {
  setInterval(function() {
    $.get(
      "yourscript.php",
      { "_": $.now() }, // disable response cache, multiple methods available.
      function(data) {
        data.forEach(function(player){
          $('<?= "#staende_$v" ?>').text("Player: " + player.id + " has data " + player.data);
        })
      }
    );
  }, 1000);
});

Your PHP should obviously load the text file, fetch the desired data and return in correct format: 您的PHP显然应该加载文本文件,获取所需的数据并以正确的格式返回:

<?php
  $content = file_get_contents('./source.txt');
  $content = explode(';', $content);

  // The array should look like this for the js to function:
  $data[] = [
    'id' => 1,
    'data' => $content[2]
  ];

  // You can append more data for other players as well, easy to loop through in JS.
  die(json_encode($data)); 
?>

There was also a little problem with browser cache, the second param in the $.get request would resolve that. 浏览器缓存也有一个小问题, $.get请求中的第二个参数可以解决该问题。 You can do "<?= $spielfile ?>?time="+$.now() instead of using the second param. 您可以执行"<?= $spielfile ?>?time="+$.now()而不是使用第二个参数。

you could search the string using a regex: 您可以使用正则表达式搜索字符串:

$(document).ready(function() {
  setInterval(function() {
    $.get(
      "<?= $spielfile ?>",
      { "_": $.now() }, // disable response cache, multiple methods available.
      function(data) {

        var val = data.replace(/.*;Player 1;([0-9]+).*/, '$1');
        $("#staende_<?= $v ?>").text(val);
      }
    );
  }, 1000);
});

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

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