Need a simple way to repeatedly poll a file using javascript
Hopefully the below is close, but I feel I'm doing the first part wrong.
Ideal outcome is status-remote.php to be polled every 2 seconds, while not being cached (hence the random nocache variable).
If it's relevant, the php file has two variables the status of which determines the visibility on this page.
<script id="status" type="text/javascript"></script>
<script type="text/javasc开发者_JAVA百科ript">
var nocache = Math.random();
setInterval(
document.getElementById('status').src = '/status-remote.php?sid=2&random='+nocache;
}, 2000);
</script>
Thanks so much for taking a look!
I think you should call Math.random()
inside the setInterval
method.
Something like this:
<script type="text/javascript">
setInterval("var nocache = Math.random();
document.getElementById('status').src =
'/status-remote.php?sid=2&random='+nocache;", 2000);
You could use a (hidden) iframe and have status-remote.php return an html document with a meta header:
<meta http-equiv="refresh" content="2" />
then parse the response via javascript in the main document.
edit: To prevent caching, I'd suggest sending the appropriate HTTP headers.
edit2: I somehow missed that it's an http-equiv meta header, so you can send an HTTP refresh header instead.
Refresh: 2; url=http://www.example.com/
This also means that you're not bound to send HTML content. Also, in the HTTP you can specify a delay and the URL to go to (in case you really want to go with the status-remote?random=random_number
cache-preventing thingy)
I would suggest using http://socket.io/ , it degrade to all browsers and uses the best available option using feature detection.
Cache:
(hence the random nocache variable)
I think you are filling up the users browser cache with a lot of crap this way. You should sent correct headers to bypass caching instead(also better for proxies).
//Set no caching
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
Pick one:
- http://enfranchisedmind.com/blog/posts/jquery-periodicalupdater-ajax-polling/
- https://github.com/blog/467-smart-js-polling
- http://925html.com/code/smart-polling/
Sidenote:
The performance/scalability is (probably) going to suck(especially if the load is NOT in memory). I think if you could you should really avoid polling. Some solutions to prevent this:
- http://pusherapp.com/: small apps(single) can use it for free. (5 Max connections, 10,000 Messages per day).
- http://socket.io: very very good node.js module to do this for you. I would advise you to watch this video from node camp giving a short introduction: "Socket.IO Workshop: Guillermo Rauch"
精彩评论