所以我的问题是我需要从其他站点更新一些数据,并且要调用该数据,我具有php函数,其中URL作为参数。 ..因此,在JS中,我创建了一个与setInterval循环的函数,在其中我用URL参数调用该php函数,并在其中存储数据,但它始终返回相同的数据。(数据实际上在流上播放,因此数据已更改每+-3分钟一次)数据仅在刷新页面(f5)上更改。.但我需要在后台更新该数据。

这是PHP函数

function get_content($URL){
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $URL);
  $data = curl_exec($ch);
  curl_close($ch);
  $data = str_replace(",,","},",$data);
  $data = str_replace("}}]}}","}]}}",$data);
  $data = str_replace("]}}","}]}}",$data);
  $data = str_replace(",}}","}}}",$data);
  $data = str_replace("}}]}}","}]}}",$data);
  return $data;


在js中,我仅在setInterval周期中调用console.log来显示php函数的结果。

console.log(<?php echo (get_content("http://server1.internetoveradio.sk:8809/status-json.xsl"));?>["icestats"]["source"])

最佳答案

是的,是的。在这种情况下,PHP仅被调用一次,即您回显了get_content()的内容。

如果要一遍又一遍地获取内容,请使用XmlHTTPRequest调用一个PHP文件,该文件然后返回get_content()的结果。

jQuery实现了ajax(XmlHTTPRequest)来做到这一点。

jQuery.ajax({
   url: "http://path.to/your_script.php",
   method: "get",
   complete: function( response ){
      console.log(response);
   }
});


编辑:
创建一个新的.php文件并将其粘贴:

<?php

function get_content($URL){
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $URL);
  $data = curl_exec($ch);
  curl_close($ch);
  $data = str_replace(",,","},",$data);
  $data = str_replace("}}]}}","}]}}",$data);
  $data = str_replace("]}}","}]}}",$data);
  $data = str_replace(",}}","}}}",$data);
  $data = str_replace("}}]}}","}]}}",$data);
  return $data;
}

echo get_content("http://server1.internetoveradio.sk:8809/status-json.xsl");


在您的html中,添加以下内容:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
    jQuery(document).ready(function(){
    jQuery.ajax({
       url: "http://path.to/your_script.php",
       method: "get",
       complete: function( response ){
           console.log(response);
       }
    });
    });
</script>


这是最基础的版本,但它应该可以为您指明正确的方向。

10-04 22:32
查看更多