Jav*_*ock 3 ajax iframe internet-explorer long-polling
我需要检查是否将命令写入txt文件以更新Web浏览器中的3D窗口.这就是所谓的"推送"技术或长轮询以通知客户端.由于浏览器必须是 Internet Explorer,我有点受限.
我想出了一个使用隐藏iframe的解决方案,该iframe调用一个php脚本,每秒重新加载以检查txt文件.
<iframe noresize scrolling="no" frameborder="0" name="loader" src="loader.php">
Run Code Online (Sandbox Code Playgroud)
loader.php基本上是这样做的:
//check txt and get commands
<body onLoad="window.setInterval('location.reload()',1000);"></body>
Run Code Online (Sandbox Code Playgroud)
我看到的唯一问题是网页浏览器中的每一秒重新加载按钮都会闪烁.虽然窗口没有闪烁,只是按钮,我仍觉得有点烦人.
有没有更好的解决方案来解决这个问题,仍然与IE兼容?
最后,经过多次尝试,我设法使其成为我认为最佳标准解决方案的工作:长轮询ajax解决方案.由于这在IE7中提出了许多问题,我将在下面粘贴我的代码.
首先是我的PHP文件,它读取一个txt并用文本回显JSON.
<?php
$commandFile = fopen("./command.txt","r");
fseek($commandFile, 0);
$command = fscanf($commandFile, "%s\n"); //reads the command
fclose($commandFile);
if($command[0] != "")
{
$commandFile = fopen("./command.txt","w"); //delete first line
fclose(commandFile);
echo json_encode($command[0]);
}
?>
Run Code Online (Sandbox Code Playgroud)
现在,HTML主页需要一种机制来递归调用函数,启动此PHP文件并检查答案.我的功能是这样的.
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript">
function longPolling()
{
$.ajaxSetup({ cache: false }); //This line is THE KEY to work under Internet Explorer
$.ajax({
type: "GET",
url: "loader.php",
dataType: 'json',
async: true,
success: function(response){
if(response!=""){
sendCommand(response); //could be any other function
}
//longPolling();
setTimeout(longPolling,1000);
},
error: function(){
//longPolling();
setTimeout(longPolling,1000);
}
});
};
$(document).ready(function(){ /*waits till the whole page loads*/
longPolling(); /*start the initial request*/
});
</script>
</body>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1074 次 |
| 最近记录: |