dtp0760 2015-09-30 08:38
浏览 84

如何在循环中使用file_get_contents?

I'm trying to use file_get_contents on loop, in order to fetch JSON string from an URL continuously (every second). And i need to store the result into a javascript variable. Here was my approach, but i didn't get any result from this. My page showed me nothing but endless loading.

<?php
    set_time_limit(0);
    while(true)
    {
    $jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php');
    echo $jsonContent;
    sleep(10);
    }

?>

And here my javascript code.

setInterval(function(){
        var jsonUpdPostData = <?php echo $jsonContent; ?>;
}, 100);

What should i do to make it work? Any suggestion will be appreciated.

  • 写回答

1条回答 默认 最新

  • dpq39825 2015-09-30 10:03
    关注

    You can make it work this way:

    getContent.php

    <?php
    echo file_get_contents('http://megarkarsa.com/gpsjson.php');
    

    xxxx.js

    setInterval(function(){
      var xmlhttp = new XMLHttpRequest();
    
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
          alert(xmlhttp.responseText); // this contains the new file contents
        }
      }
    
      xmlhttp.open('GET', 'getContent.php');
      xmlhttp.send();
    }, 100);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line