<script type="text/javascript">
var t;
function tick() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200 && document.getElementById("txtHint").innerHTML!=xmlhttp.responseText) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","http://ubarskit.com/v/response.php",true);
xmlhttp.send();
t=setTimeout("tick()",1000);
}
</script>
</head>
<body onload="tick()">
<span id="txtHint"></span>
</body>
我希望它每秒都从response.php更新span-tag中的文本。 适用于chrome,但不适用于Firefox或Opera。
这是response.php文件:
<?php
if(isset($_GET['ropa']))
{
$fp = fopen('shout.txt', w);
fwrite($fp, $_GET['ropa']);
fclose($fp);
}
else
{
echo file_get_contents('shout.txt');
}
?>
答案 0 :(得分:1)
我会通过添加一些调试输出来验证状态是否符合预期。如果它返回状态0,则可能存在跨域安全问题。
<script type="text/javascript">
var t;
function tick() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
document.getElementById("debug").innerHTML = "readyState: " + xmlhttp.readyState + "<br />status: " + xmlhttp.status;
if (xmlhttp.readyState==4 && xmlhttp.status==200 && document.getElementById("txtHint").innerHTML!=xmlhttp.responseText) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","http://ubarskit.com/v/response.php",true);
xmlhttp.send();
t=setTimeout("tick()",1000);
}
</script>
</head>
<body onload="tick()">
<span id="debug"></span>
<span id="txtHint"></span>
</body>
答案 1 :(得分:0)
而不是像真人一样,我使用jQuery;)
<script type="text/javascript">
function tick() {
$.get('response.php',function(data) {
$('#txtHint').html(data);
});
}
function submitShout(form){
$.get('response.php',{ ropa: form.elements['ropa'].value});
}
</script>
</head>
<body onload="window.setInterval('tick()',1000)">
<span id="txtHint"></span>
<form action="response.php" method="get" onsubmit="submitShout(this); return false;">
<input type="text" id="ropa" name="ropa">
</form>