我对 PHP/Ajax/Html 很陌生,所以这是我的宝贝问题(我正在制作一个广播电台网站),
test.php向我的服务器查询当前正在播放的歌曲名称。
listen.php在 'refreshTitle' div 标签中显示这首歌的名称。
当我的电台改变歌曲时,会有 30 秒的延迟,所以我想做的是每秒获取歌曲标题,如果标题与实际听到的不同,则比较/延迟显示的更新,很容易对?!这是listen.php:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if (window.XMLHttpRequest) { // for Firefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxrequest(php_file, tagID) {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
// create pairs index=value with data that must be sent to server
var d = new Date();
var t = d.toLocaleTimeString();
var the_data = 'test=' + t;
//append time purely for testing to make sure text updates
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function () {
if (request.readyState == 4) {
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
setInterval(
function () {
ajaxrequest('test.php', 'refreshTitle')
}, 1000); // refresh every 10000 milliseconds
//This time val should vary based on the song title retrieved during the last second
</script>
在页面其余部分的某个地方,我有这个:
echo "<div id=\"refreshTitle\" style=\"float:left; padding-top:6px;\">\n";
echo "</div>\n";
在test.php(带有歌曲名称的文件)中,我有这个:
if (isset($_POST['test'])) {
$str = $_POST['test']; // get data
echo $dnas_data['SONGTITLE'] . " Current time " . $str;
}
所以基本上每一秒我都会将时间发送到test.php,它会回显它,并且我假设的那个回显会用这一行放入“refreshTitle”中:
document.getElementById(tagID).innerHTML = request.responseText;
我想要做的是在listen.php中将歌曲标题放入我的javascript中,并且只在一些字符串比较/延迟逻辑之后运行ajax请求。
对不起,冗长的描述,但我很困惑,并认为我已经完成了这整件事:) 请让我知道任何想法......