• 我的第一个comet长连接例子


    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
    <title>大家来玩Comet</title>
    <script src="../statics/js/jquery-1.9.1.min.js"></script>
    <script src="../statics/js/plugins/placeholder.js"></script><!--让IE10以下也支持placeholder-->
    <style type="text/css">
    #word{width:450px;height:40px;padding:0 10px;border:#ddd 2px solid; line-height:40px9}
    #btn{height:44px; vertical-align:middle;position:relative;top:-2px;+vertical-align:bottom;+top:-1px;}
    #content{width:644px;height:300px;+width:720px;margin:0 auto;background:#f7f7f7;padding:10px; overflow:hidden;overflow-y:auto}
    .talkCloud{text-align:left;line-height:40px;}
    
    
    </style>
    </head>
    <body>
    <script type="text/javascript">
    $(function(){
        
        /*cookie 操作*/
        var cookieUtil = {
            //获取cookie
            get:function(name){
                var cookieName = encodeURIComponent(name)+"=",
                    cookieStart = document.cookie.indexOf(cookieName),
                    cookieValue = null;
                
                if(cookieStart>-1){
                    var cookieEnd = document.cookie.indexOf(";",cookieStart);
                    if(cookieEnd==-1){
                        cookieEnd = document.cookie.length;
                    }
                    cookieValue = decodeURIComponent(document.cookie.substring(cookieStart+cookieName.length,cookieEnd));
                }
                return cookieValue;
            },
            
            //设置cookie
            set:function(name,value,expires,path,domain,secure){
                var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
                if(expires instanceof Date){
                    cookieText += "; expires="+expires.toGMTString();
                }
                if(path){
                    cookieText += "; path=" + path;
                }
                if(domain){
                    cookieText += "; domain" + domain;
                }
                if(secure){
                    cookieText += "; secure";
                }
                document.cookie = cookieText;
                return value;
            },
            
            //删除cookie
            unset:function(name,path,domain,secure){
                this.set(name,"",new Date(0),path,domain,secure);    
            }
        };
        window.cookieUtil = cookieUtil;
        
        
        
        //comet长连接例子
        var clickTimes = 0;//点击计数
        var timestamp = 0;//文件时间戳
        var url = 'server.php';//后端服务器脚本地址
        var noerror = true;
        var ajax;
     
        function handleResponse(response){
            $('#content').append('<div class="talkCloud">' + response['msg'] + '</div>');
            $("#content").scrollTop($("#content")[0].scrollHeight);
        }
        function connect() {
            ajax = $.ajax(url, {
                type: 'get',
                data: { 'timestamp' : timestamp,'uname' : cookieUtil.get("uname")},
                success: function(transport) {
                    eval('var response = '+transport);
                    timestamp = response['timestamp'];
                    handleResponse(response);
                    noerror = true;//判断ajax发送成功的回调函数是否执行成功的标志;
                },
                complete: function(transport) {
                    (!noerror) && setTimeout(function(){ connect() }, 5000) || connect();
                    noerror = false;//执行完一次完成回调函数是否执行成功的标志
                }
            });
        }
     
        function doRequest(request) {
            $.ajax(url, {
                type: 'get',
                data: { 'msg' : request,'uname':cookieUtil.get("uname") }
            });
        };
        
        $('#cometForm').on("submit",function(){
            clickTimes++;
            if(clickTimes == 1){
                cookieUtil.set("uname",$('#word').val(),'','','','');
            };
            doRequest($('#word').val());
            $('#word').val('');
            return false;
        });
        
        
        connect();
    
    });
    </script>
    <center>
    <h2>大家来玩长连接</h2>
    <div id="content"></div>
    <div style="margin: 5px 0;">
    <form action="javascript:void(0);" id="cometForm" method="get">
    <input id="word" name="word" type="text" value="" placeholder="第一次请输入你自己的姓名">
    <input name="submit" type="submit" id="btn" value="我就是个摆设,其实敲回车也可以提交">
     
    </form></div>
    </center>
    </body>
    </html>
    <?php
     
    $filename  = 'F:phpStudyWWWosscometDemodata.txt';
    
    // 消息都储存在这个文件中
    $msg = isset($_GET['msg']) ? $_GET['msg'] : '';
    $uname = isset($_GET['uname']) ? $_GET['uname']:'';
    
    if ($msg != ''){
            
        
        //fopen()方法:如果文件不存在,则创建,如果存在则打开文件。它的第二个参数是打开的文件的模式,w表示覆盖式只写,详见《PHP高程设计》183页
    //    $fn = fopen($filename,'w');
    //    fwrite($fn,$uname.": ".$msg);
    //    fclose($fn);
            file_put_contents($filename,$uname.": ".$msg); //此方法已不建议使用
        
        
        //    file_put_contents($filename,"您的名字是: ".$msg);
        
        
    
    
        
    }
    
        // 不停的循环,直到储存消息的文件被修改
        $lastmodif    = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
        $currentmodif = filemtime($filename);
        while ($currentmodif <= $lastmodif){ // 如果数据文件已经被修改
            usleep(100000); // 100ms暂停 缓解CPU压力
            clearstatcache(); //清除缓存信息
            $currentmodif = filemtime($filename);
        }
     
        // 返回json数组
        $response = array();
        $response['msg']       = file_get_contents($filename);
        $response['timestamp'] = $currentmodif;
        echo json_encode($response);
        flush();
    
     
    ?>
    placeholder.js 这个东西也不错,贴在这里,省的去找了:
    (function($) {  
      /** 
       * http://blog.csdn.net/mycwq/ 
       * 2012/11/28 15:12 
       */  
      
      var placeholderfriend = {  
        focus: function(s) {  
          s = $(s).hide().prev().show().focus();  
          var idValue = s.attr("id");  
          if (idValue) {  
            s.attr("id", idValue.replace("placeholderfriend", ""));  
          }  
          var clsValue = s.attr("class");  
          if (clsValue) {  
            s.attr("class", clsValue.replace("placeholderfriend", ""));  
          }  
        }  
      }  
      
      //判断是否支持placeholder  
      function isPlaceholer() {  
        var input = document.createElement('input');  
        return "placeholder" in input;  
      }  
      //不支持的代码  
      if (!isPlaceholer()) {  
        $(function() {  
      
          var form = $(this);  
      
          //遍历所有文本框,添加placeholder模拟事件  
          var elements = form.find("input[type='text'][placeholder]");  
          elements.each(function() {  
            var s = $(this);  
            var pValue = s.attr("placeholder");  
            var sValue = s.val();  
            if (pValue) {  
              if (sValue == '') {  
                s.val(pValue);  
              }  
            }  
          });  
      
          elements.focus(function() {  
            var s = $(this);  
            var pValue = s.attr("placeholder");  
            var sValue = s.val();  
            if (sValue && pValue) {  
              if (sValue == pValue) {  
                s.val('');  
              }  
            }  
          });  
      
          elements.blur(function() {  
            var s = $(this);  
            var pValue = s.attr("placeholder");  
            var sValue = s.val();  
            if (!sValue) {  
              s.val(pValue);  
            }  
          });  
      
          //遍历所有密码框,添加placeholder模拟事件  
          var elementsPass = form.find("input[type='password'][placeholder]");  
          elementsPass.each(function(i) {  
            var s = $(this);  
            var pValue = s.attr("placeholder");  
            var sValue = s.val();
            if (pValue) {  
              if (sValue == '') {  
                //DOM不支持type的修改,需要复制密码框属性,生成新的DOM  
                var html = this.outerHTML || "";  
                html = html.replace(/s*type=(['"])?password1/gi, " type=text placeholderfriend")  
                  .replace(/s*(?:value|on[a-z]+|name)(=(['"])?S*1)?/gi, " ")  
                  .replace(/s*placeholderfriend/, " placeholderfriend value='" + pValue  
                  + "' " + "onfocus='placeholderfriendfocus(this);' ");  
                var idValue = s.attr("id");
                if (idValue) {
                  s.attr("id", idValue + "placeholderfriend");
                }
                var clsValue = s.attr("class");  
                if (clsValue) {  
                  s.attr("class", clsValue + "placeholderfriend");  
                }  
                s.hide();  
                s.after(html);  
              }  
            }  
          });  
      
          elementsPass.blur(function() {  
            var s = $(this);  
            var sValue = s.val();  
            if (sValue == '') {  
              var idValue = s.attr("id");  
              if (idValue) {  
                s.attr("id", idValue + "placeholderfriend");  
              }  
              var clsValue = s.attr("class");  
              if (clsValue) {  
                s.attr("class", clsValue + "placeholderfriend");  
              }  
              s.hide().next().show();  
            }  
          });  
      
        });  
      }  
      window.placeholderfriendfocus = placeholderfriend.focus;  
    })(jQuery);

    HTML5 shiv也贴上来:

    /*
     HTML5 Shiv v3.6.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed.g
    */
    (function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag();
    a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/w+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x<style>article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}</style>";
    c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="<xyz></xyz>";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode||
    "undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup main mark meter nav output progress section summary time video",version:"3.6.2",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f);if(g)return a.createDocumentFragment();
    for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d<h;d++)c.createElement(e[d]);return c}};l.html5=e;q(f)})(this,document);
    window._browserIsNotSupported = true;
    if(window.attachEvent){
      window.attachEvent('onload', function(){
        var lowestSupportedIEVersion = 8;
        if(window.LOWEST_IE_VERSION != undefined){
          lowestSupportedIEVersion = window.LOWEST_IE_VERSION;
        }
        var el = document.createElement('div'),
            elStyle = el.style,
            docBody = document.getElementsByTagName('body')[0],
            linkStyle = 'color:#06F;text-decoration: underline;';
        el.innerHTML =    '尊敬的小伙伴们:<br />'+
            '使用慧业网Boss/CRM系统控制台需要安装Internet Explorer 8或更新版本的浏览器,'+
            '请<a href="http://windows.microsoft.com/zh-cn/internet-explorer/download-ie" style="'+linkStyle+'" target="_blank">下载安装IE' + lowestSupportedIEVersion + '</a>(或更新)。'+
            '也可以在其他浏览器,'+
            '如<a href="http://rj.baidu.com/soft/detail/14744.html" style="'+linkStyle+'" target="_blank">Chrome</a>'+
            '或<a href="http://www.firefox.com.cn/download/" style="'+linkStyle+'" target="_blank">Firefox</a>火狐中打开本系统。';
        // elStyle.width = '100%';
        elStyle.width = '720px';
        elStyle.color = '#000';
        elStyle.fontSize = '14px';
        elStyle.lineHeight = '200%';
        elStyle.margin = '60px auto';
        elStyle.backgroundColor = '#fffbd5';
        elStyle.border = '1px solid #CCC';
        elStyle.padding = '24px 48px';
        // elStyle.background = '#F00 url(styles/images/not-support-ie67.png) 48px 48px no-repeat';
        // elStyle.padding = '40px 40px 48px 160px';
        docBody.innerHTML = '';
        docBody.appendChild(el);
        // docBody.insertBefore(el,docBody.firstChild);
      });
    }
  • 相关阅读:
    google code jam exercise——Your Rank Is Pure
    C/C++中的文件操作(2)
    google code jam exercise——File Fix It
    google code jam exercise——All Your Base
    C/C++中的文件操作(1)
    google code jam exercise——Center of Mass
    C/C++字符串操作split
    JavascriptDOM
    Javascript特权方法
    Report子报表
  • 原文地址:https://www.cnblogs.com/macliu/p/5229170.html
Copyright © 2020-2023  润新知