duandu1966 2013-10-27 10:28
浏览 58

纯javascript longpolling聊天

So I have started a project, where I want to make an online ajax chat, but I do NOT want to use jQuery JSON, COMET and so on. I am looking for pure javascript, no libraries no framework.

Good news is that I have already made the chat and it is working fine. Why do i make this post? Because I simply cannot find any pure javascript solution for long-polling. Currently I am using the setInterval method to "ask" the database to send whatever is in the database. now, how do I execute my ajax request whenever I get a response? (Long-polling).

please bear in mind that I am not looking for a jQuery solution or what have you.. I am using pure JavaScript and PHP. No framework or library.

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • doucang5542 2013-10-28 18:44
    关注

    i believe this is relatively close to what your looking for - referencing a vanilla js ajax tutorial on nettuts plus:

    load('test.txt', function(xhr) { 
        document.getElementById('container').innerHTML = xhr.responseText;  
        // you would obviously custom tailor this peice to utilize your specific data
    });  
    
    function load(url, callback) {  
        var xhr;  
    
        if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();  
        else {  
            var versions = ["MSXML2.XmlHttp.5.0",   
                            "MSXML2.XmlHttp.4.0",  
                            "MSXML2.XmlHttp.3.0",   
                            "MSXML2.XmlHttp.2.0",  
                            "Microsoft.XmlHttp"]  
    
             for(var i = 0, len = versions.length; i < len; i++) {  
                try {  
                    xhr = new ActiveXObject(versions[i]);  
                    break;  
                }  
                catch(e){}  
             } // end for  
        }  
    
        xhr.onreadystatechange = ensureReadiness;  
    
        function ensureReadiness() {  
            if(xhr.readyState < 4) {  
                return;  
            }  
    
            if(xhr.status !== 200) {  
                return;  
            }  
    
            // all is well    
            if(xhr.readyState === 4) {  
                callback(xhr);  
            }             
        }  
    
        xhr.open('GET', url, true);  
        xhr.send('');  
    }
    

    and you could build your "success" handlers into the 'ensure readiness' based on the return values

    heres a link to the nettuts tutorial

    and another to the MDN ajax API docs

    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置