Using iframe for “long polling” withouth causing flashing browser

大城市里の小女人 提交于 2020-01-14 14:45:16

问题


I need to check if commands are written to a txt file in order to update a 3D window inside my web browser. This is what is known as "push" technique or long polling to notify the client. As the browser has to be Internet Explorer I am a bit limited.

I have come up with a solution using a hidden iframe that calls a php script that reloads every second to check the txt file.

<iframe noresize scrolling="no" frameborder="0" name="loader" src="loader.php">  

The loader.php basically does this:

//check txt and get commands
<body onLoad="window.setInterval('location.reload()',1000);"></body>

The only problem I see is that every second in the web browser the reload button flashes. Although the window is not flashing, just the button, I still find it a bit annoying.

Is there a better solution for this problem, still compatible with IE?


回答1:


Finally, after many tries I managed to make it work which I consider the optimal standard solution: a long polling ajax solution. As this gives many problems in IE7, I will paste my codes below.

First my PHP file, which reads a txt and echoes a JSON with the text.

<?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]);  
}
?>

Now, the HTML main page needs a mechanism to call a function recursively that launchs this PHP file and checks the answer. My function is something like this.

<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>


来源:https://stackoverflow.com/questions/15613623/using-iframe-for-long-polling-withouth-causing-flashing-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!