【发布时间】:2013-08-05 11:42:45
【问题描述】:
我在我的电台网站上使用 JavaScript 歌曲倒计时。
由于 ajax 调用检查是否有新歌,倒计时每 10 秒滞后一次(再跳 1 秒):
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;
?>
【问题讨论】:
-
不要让异步调用同步;)
-
@Jeffman 是正确的。如果不需要,请删除
async: false(默认为隐式async: true)。 -
它不适用于 async = true。
-
因为在我这样做之后:gcs = getcursong(); gcs 为空,因为 async=true。我能做什么?
-
好的,我发现:function () { var result = null; var scriptUrl = "get_current_song.php"; $.ajax({ url: scriptUrl, type: 'get', dataType: 'html', async: true, success: function(data) { song = $('#song').html(); if (data ! = song && data != ""){ setTimeout(function (){ $('#nowplaying').load('nowplaying.php'); }, 5000); // pourquoi fadeIn("slow"); ?! ? } } }); }, 10000);
标签: php javascript ajax curl