我在我的電臺網站上使用javascript歌曲倒計時。由於阿賈克斯調用javascript倒計時滯後
在每10秒,倒計時滯後(跳過1一個多秒),因爲Ajax調用來檢查是否有新的歌曲:
function getcursong(){
var result = null;
var scriptUrl = "get_current_song.php";
$.ajax({
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
在控制檯看,我看到GET
通話約需2秒鐘。
get_current_song.php
使用curl
從icecast服務器獲取當前歌曲。
有什麼我可以做的,以防止由於那些Ajax調用的滯後倒計時?
以下是get_current_song.php
。
<?php
require('config.php');
$current_song = getStreamInfo();
function url_get_contents($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_TIMEOUT,2);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
function getStreamInfo(){
$str = url_get_contents(SERVER.'/status.xsl?mount='.MOUNT);
if(preg_match_all('/<td\s[^>]*class=\"streamdata\">(.*)<\/td>/isU', $str, $match)){
$x = explode(" * ",$match[1][9]);
return $x[1];
}
}
?>
<?php
echo $current_song;
?>
不要使異步調用同步;) – Andreas
@Jeffman是正確的。如果你不需要它,刪除'async:false'(默認是一個隱含的'async:true')。 – ale
謝謝!就是這樣。 – trogne