连续调用 XMLHttpRequest [英] Calling a XMLHttpRequest continuously

查看:41
本文介绍了连续调用 XMLHttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在以 setInterval 为基础调用一个函数.

At the moment I am calling a function on a setInterval basis.

此函数向我的服务器发出 XMLHttpRequest 以获取更新信息.如果有可用更新,我会更新图像(使用画布元素).

This function makes a XMLHttpRequest to my server to get update info. If there is an update available I update an image (using canvas element).

这是做这种事情的最佳方式吗?

Is this the optimum way to do this sort of thing?

我的代码:

调用代码:

    function StartFeedUp() {
        if (tmrStartFeedUp) window.clearInterval(tmrStartFeedUp);
        tmrStartFeedUp = setInterval(GetNextImage, 330);
    }

我调用的函数:

  var isProcess = false;

  function GetNextImage() {
        try {
            if (!isProcess) {
                isProcess = true;
                var urlTS = '/Cloud/isNewFrames.ashx?alias=' + alias + '&version=' + version + '&guidlogon=' + guidlogon;
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.open("GET", urlTS, true);                  
                xmlhttp.timeout = 200;
                xmlhttp.send();
                var nextts = xmlhttp.responseText;
             }
                 isProcess = false;
             }
         catch (err) {
            isProcess = false;
            document.getElementById("divMode2").innerHTML = err;
        } 
    }

推荐答案

除了重复 XHR 调用,你可以使用 HTML5 Web Sockets 允许您保持与服务器的连接,从而服务器将在需要时推送数据.Web Sockets 相对较新,因此旧浏览器不支持.

Other than repeating the XHR call, you can use HTML5 Web Sockets which allows you to maintain a connection to the server, whereby the server would push data as and when needed. Web Sockets are relatively new and so aren't supported by old browsers.

你的 XHR 是异步的,所以你应该监听 onreadystatechange 事件,而不是总是期望响应在 send() 调用之后直接可用:

Your XHR is asyncronous so you should be listening on the onreadystatechange event instead of always expecting the response to be available directly after the send() call:

xmlhttp.open("GET", urlTS, true);                  
xmlhttp.timeout = 200;
xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        console.log("received " + xmlhttp.responseText);
    }
}
xmlhttp.send();

这篇关于连续调用 XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆