• 10、json数据页面展示、富文本编辑器 、form大文件和小文件上传、三种下载、JSONP、请求方式和ajax请求、form标签的属性、cookie、localStorage、sessionStorage、DOM元素的增删改查、算法知识、显示屏尺寸、编程绝句、滚动条破坏布局、杂


    一、json数据页面展示
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.2.1/jquery.js"></script>
      <style > 
        .json-document {
          padding: 1em 2em;
        }
        ul.json-dict, ol.json-array {
          list-style-type: none;
          margin: 0 0 0 1px;
          border-left: 1px dotted #ccc;
          padding-left: 2em;
        }
        .json-string {
          color: #0B7500;
        }
        .json-literal {
          color: #1A01CC;
          font-weight: bold;
        }
        a.json-toggle {
          position: relative;
          color: inherit;
          text-decoration: none;
        }
        a.json-toggle:focus {
          outline: none;
        }
        a.json-toggle:before {
          font-size: 1.1em;
          color: #c0c0c0;
          content: "25BC"; 
          position: absolute;
          display: inline-block;
           1em;
          text-align: center;
          line-height: 1em;
          left: -1.2em;
        }
        a.json-toggle:hover:before {
          color: #aaa;
        }
        a.json-toggle.collapsed:before {
          transform: rotate(-90deg);
        }
        a.json-placeholder {
          color: #aaa;
          padding: 0 1em;
          text-decoration: none;
        }
        a.json-placeholder:hover {
          text-decoration: underline;
        }
      </style>
    </head>
    <body>
      <div id="aaa"></div>
    </body>
    </html>
    <script>
      (function ($) {
        function isCollapsable(arg) {
          return arg instanceof Object && Object.keys(arg).length > 0;
        }
        function isUrl(string) {
          var urlRegexp = /^(https?://|ftps?://)?([a-z0-9%-]+.){1,}([a-z0-9-]+)?(:(d{1,5}))?(/([a-z0-9-._~:/?#[]@!$&'()*+,;=%]+)?)?$/i;
          return urlRegexp.test(string);
        }
        function json2html(json, options) {
          var html = '';
          if (typeof json === 'string') {
            json = json
              .replace(/&/g, '&')
              .replace(/</g, '<')
              .replace(/>/g, '>')
              .replace(/'/g, '&apos;')
              .replace(/"/g, '"');
      
            if (options.withLinks && isUrl(json)) {
              html +=
                '<a href="' +
                json +
                '" class="json-string" target="_blank">' +
                json +
                '</a>';
            } else {
              if (json.indexOf('RED_SELF') > -1) {
                json = json.replace('RED_SELF', '');
                html +=
                  '<span class="json-literal" style="color:red">' + json + '</span>';
              } else if (json.indexOf('RED_parent') > -1) {
                json = json.replace('RED_parent', '');
                html += '<span class="json-literal RED_parent">' + json + '</span>';
              } else {
                json = json.replace(/"/g, '\"');
                html += '<span class="json-string">"' + json + '"</span>';
              }
            }
          } else if (typeof json === 'number') {
            html += '<span class="json-literal">' + json + '</span>';
          } else if (typeof json === 'boolean') {
            html += '<span class="json-literal">' + json + '</span>';
          } else if (json === null) {
            html += '<span class="json-literal">null</span>';
          } else if (json instanceof Array) {
            if (json.length > 0) {
              html += '[<ol class="json-array">';
              for (var i = 0; i < json.length; ++i) {
                html += '<li>';
                if (isCollapsable(json[i])) {
                  html += '<a href class="json-toggle"></a>';
                }
                html += json2html(json[i], options);
                if (i < json.length - 1) {
                  html += ',';
                }
                html += '</li>';
              }
              html += '</ol>]';
            } else {
              html += '[]';
            }
          } else if (typeof json === 'object') {
            var keyCount = Object.keys(json).length;
            if (keyCount > 0) {
              html += '{<ul class="json-dict">';
              for (var key in json) {
                if (Object.prototype.hasOwnProperty.call(json, key)) {
                  html += '<li>';
                  var keyRepr = options.withQuotes
                    ? '<span class="json-string">"' + key + '"</span>'
                    : key;
                  if (isCollapsable(json[key])) {
                    html += '<a href class="json-toggle">' + keyRepr + '</a>';
                  } else {
                    html += keyRepr;
                  }
                  html += ': ' + json2html(json[key], options);
                  if (--keyCount > 0) {
                    html += ',';
                  }
                  html += '</li>';
                }
              }
              html += '</ul>}';
            } else {
              html += '{}';
            }
          }
          return html;
        }
        $.fn.jsonViewer = function (json, options) {
          options = Object.assign(
            {},
            {
              collapsed: false,
              rootCollapsable: true,
              withQuotes: false,
              withLinks: true
            },
            options
          );
          return this.each(function () {
            var html = json2html(json, options);
            if (options.rootCollapsable && isCollapsable(json)) {
              html = '<a href class="json-toggle"></a>' + html;
            }
            $(this).html(html);
            $(this).addClass('json-document');
            $(this).off('click');
            $(this).on('click', 'a.json-toggle', function () {
              var target = $(this)
                .toggleClass('collapsed')
                .siblings('ul.json-dict, ol.json-array');
              target.toggle();
              if (target.is(':visible')) {
                target.siblings('.json-placeholder').remove();
              } else {
                var count = target.children('li').length;
                var placeholder = count + (count > 1 ? ' items' : ' item');
                target.after(
                  '<a href class="json-placeholder">' + placeholder + '</a>'
                );
              }
              return false;
            });
            $(this).on('click', 'a.json-placeholder', function () {
              $(this).siblings('a.json-toggle').click();
              return false;
            });
      
            if (options.collapsed == true) {
              $(this).find('a.json-toggle').click();
            }
          });
        };
      })(jQuery);
      var obj={
        "id": 1001,
        "type": "donut",
        "name": "Cake",
        "description": "https://en.wikipedia.org/wiki/Doughnut",
        "price": 2.55,
        "available": {
          "store": 42,
          "warehouse": 600
        },
        "toppings": [
          { "id": 5001, "type": "None" },
          { "id": 5002, "type": "Glazed" },
          { "id": 5005, "type": "Sugar" },
          { "id": 5003, "type": "Chocolate" },
          { "id": 5004, "type": "Maple" }
        ],
        "uuids": [
          "826b23ce-2669-4122-981f-3e2e4429159d",
          "e32111a0-6a87-49ab-b58f-a01bf8d28ba0",
          "c055a894-698e-41c0-b85f-7510a7351d9d",
        ],
      };
      $('#aaa').jsonViewer(obj);
    </script>
     
    二、富文本编辑器 editor.md 的使用            
    1、下载依赖包并导入 git clone https://github.com/pandao/editor.md.git    
    <script src="./common/editor.md/editormd.min.js"></script>        
    2、如果编辑后台返回的数据,那么向后台发送请求,获取数据serverData
    3、执行下列代码
      that.testEditor = editormd("editormd", {
         "100%",
        height: "720",
        watch: false, //关闭分栏
        toolbar: false, //关闭工具栏
        value: serverData||'',
        path: "./common/editor.md/lib/",//依赖存放路径
      });
      setTimeout(function () {
        var value = that.testEditor.getValue();//获取编辑数据
      }, 500);
    4、详细使用教程,百度“editor.md使用教程”
    
    三、form大文件上传示例
    <script src="./common/webuploader.js"></script>
    <button type="button" id="updataButton">升级</button>
    <style>
      #updataButton input[type="file"] {
        display: none;
      }
    </style>  
    //页面初始化的时候执行下面代码
    var files;
    var task_id = WebUploader.Base.guid();
    var uploader = WebUploader.create({
      server: './system/devinfo/upload',
      pick: '#updataButton',
      auto: false,//需要手动上传
      chunked: true,//需要分片
      chunkSize: 20 * 1024 * 1024,//每片大小
      chunkRetry: 3,//如果某个分片由于网络问题出错,允许自动重传3次
      threads: 1,//允许同时最大上传进程数为1
      duplicate: true,//需要去重
      formData: {//文件上传请求的参数表,每次发送都会发送此对象中的参数
        task_id: task_id,
      },
      fileVal:'rule'//设置文件上传域的name
    });
    uploader.on('fileQueued', function (file) {
      files = file;
      //有交互:列队完成,告知后台,准备接受数据
      //返回成功后执行:uploader.upload();开始上传,无前后台交互
      //返回失败执行:uploader.removeFile(files); 
    }).on('fileDequeued', function () {
      //console.log('remove queue success.');
    }).on('startUpload', function () {
      $scope.updata();//无前后台交互,出现弹窗,告知正在上传
    }).on('uploadProgress', function (file, percentage) {
      //上传中,出现进度条
    }).on('uploadSuccess', function (file) {
      //交互一、告知后台,数据发送完毕
      //交互二、定时询问后台,是否更新完毕
    }).on('uploadError', function () {
      //上传出错
    });
    
    四、form小文件上传示例
    1、原生事件中,这里默认传入实参this,指的是input上传的内容.
    2、在angular1事件中,这里为空,所以需要用原生事件,调用angular1方法.
    3、原生事件中调用angular方法, 比如input的onChange事件想调用angular里面定义的方法onChange
    <form enctype="multipart/form-data" method="post" id="formID">
      <div class="form-inline protocol-private-row">
        <div class="form-group">
          <label>
            <span>*</span>
            <span>协议名称</span>
          </label>
          <input type="text" class="form-control" name="name" ng-model="thisForm.name"
            id="protocolID" style="padding-left: 50px;400px;" maxlength="40">
          <span class="pre-protocol-string">UDF-</span>
        </div>
      </div>
      <div class="form-inline protocol-private-row">
        <div class="form-group">
          <label>
            <span>*</span>
            <span>协议脚本</span>
          </label>
          <button type="button" >
            选择文件        //注意:鼠标对象和元素对象
            <input type="file" name="rule" onchange="angular.element(this).scope().fileChangedOne(this)">
          </button>
          <span>{{uploadOne[0].name||'请选择 .lua格式文件'}}</span>
        </div>
      </div>
      <div class="form-inline protocol-private-row">
        <div class="form-group ">
          <label>
            <span>*</span>
            <span>协议描述</span>
          </label>
          <button type="button" >
            选择文件
            <input type="file" name="segment" onchange="angular.element(this).scope().fileChangedTwo(this)">
          </button>
          <span>{{uploadTwo[0].name||'请选择 .proto格式文件'}}</span>
        </div>
      </div>
      <div class="form-inline protocol-private-row">
        <div class="form-group">
          <label></label>
          <button type="submit" ng-click="startUpload()" style=" 250px" class="btn btn-primary"
            ng-disabled="!uploadOne[0].name||!uploadTwo[0].name||!thisForm.name">导入</button>
        </div>
      </div>
    </form>
    $scope.fileChangedOne = function (ele) {
      $scope.uploadOne = ele.files;
      $scope.$apply();
    };
    $scope.fileChangedTwo = function (ele) {
      $scope.uploadTwo = ele.files;
      $scope.$apply();
    };
    $scope.startUpload = function () {
      var formdata = new FormData(document.getElementById('formID'));
      var protocolName = $('#protocolID').val();
      formdata.set('name', ('UDF-'+protocolName));
      $.ajax({
        url: '/protocol/selfdefine/upload',
        type: 'post',
        data: formdata,
        processData: false,//数据不编码
        contentType: false,//不改变enctype="multipart/form-data"
        success: function (res) {
          if (res.status === 1) {
            $scope.g_tip('上传成功!');
            $scope.pagin_init.reload();
            $scope.uploadOne = '';
            $scope.uploadTwo = '';
            $scope.thisForm.name = '';
            angular.element('input[type = file]')[0].value = '';
            angular.element('input[type = file]')[1].value = '';
          } else if (res.status === 0) {
            $scope.g_alert(res.msg);
          } else if (res.status === 1000) {
            dir_alert.set({
              button: true,
              cancel_hiden: true,
              click_other_hidden: false,
              icon_close: false,
              title: '错误',
              content: '当前会话已过期,即将跳到登录页。',
            });
            account_m.exit();
          } else {
            $scope.g_alert('上传失败!');
          }
        },
        error: function () {
          $scope.g_alert('通信失败!');
        }
      });
    };
    
    五、三种下载
    1、a下载,普通JS下载后台文件。
    下面后台返回的data为json数据,不是某种格式的文件。
    function down(data) {
      var a = document.createElement('a');
      document.body.appendChild(a);
      a.download = '111.txt';
      a.href = URL.createObjectURL(data);
      a.click();
      a.remove();
    }; 
    function down(url) {
      var a = document.createElement('a');
      document.body.appendChild(a);
      a.download = '111.txt';
      a.href = url;
      a.click();
      a.remove();
    }; 
    2、Excel下载
    (1)引入插件xlsx.core.min.js和alasql.min.js
    (2)代码如下:
    var tableTh=["times [时间]", "user [用户]", "ip [IP地址]", "result [登录结果]"];
    var title="文件名"
    var dataArray=[
      {
        times: "2003-03-04",//0
        user: "wdsfm",//1
        ip: "216.94.168.85"//2
        result: 1,//3
        ServiceType: "yhzuu",
        id: 1,
        operation: "刷新页面",
      },{
        times: "2003-03-04",//0
        user: "wdsfm",//1
        ip: "216.94.168.85"//2
        result: 1,//3
        ServiceType: "yhzuu",
        id: 2,
        operation: "刷新页面", 
      }
    ];
    alasql('SELECT'+ tableTh+ 'INTO XLSX("'+ title+ '.xlsx",{headers:true}) FROM ?', dataArray);
    3、PDF下载
    (1)如果想通过纯前端技术实现文件下载,直接把a标签的href属性设置为文件路径即可,<a href = "https://cdn.shopify.com/s/Manaul.pdf" download = "test.pdf"> 下载</a>。txt、jpg、pdf等格式的文件,浏览器支持直接打开,
    (2)PDF版报告的展示
    <script src="/audit-html/static/common/jquery-media.js"></script>
    步骤一:告诉后台我要下载文件,后台同意
    步骤二:执行下面代码
    $('#handout_wrap_inner').media({
       '100%',
      height: '680px',
      autoplay: true,
      src: url//后台存放pdf文件的地方
    });
    
    六、JSONP
    1、Ajax,在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页内容。
    2、Ajax请求存在因同源策略而导致的跨域无权限访问的问题。
    3、凡是拥有”src”这个属性的标签都拥有跨域的能力,比如<script>、<img>、<iframe>)。
    4、JSONP的一般使用过程是,定义myCallback函数,添加一个<script>标签,通过问号传参的形式?callback=myCallback传给服务器;服务器收到参数后,以字符串的形式"myCallback({key:{key:value}})"返回JSON数据,浏览器把字符串里的内容当作script代码来执行,类似于eval函数。
    <script type="text/javascript">
      function fn(data) {
        console.log(data);
        console.log($);
      }
    </script>
    <script type="text/javascript" src="http://matchweb.sports.qq.com/kbs/hotMatchList?callback=myCallback"></script>
    5、在jquery中,jsonp的实现方式是:在动态添加的<script>标签里执行(经过ajax请求后)服务器返回的js脚本(valueCallback函数的执行),js脚本执行完毕后,<script>标签和js脚本被移除。 
    6、以下是jQuery中ajax的配置与地址栏显示的对应关系,如地址栏默认为:url?callback=jQuery123&other。 
    $.ajax({ 
      data:{},//规定要发送到服务器的数据。 
      dataType:"jsonp",//预期的服务器响应的数据类型。   
      jsonp:"keyCallback",//重写回调函数的字符串。用服务器给的keyCallback取代jQuery默认的callback。   
      jsonpCallback:"valueCallback",//规定回调函数的名称。用服务器给的valueCallback取代jQuery默认的jQuery123,本地需要定义valueCallback函数来利用服务器返回的"valueCallback(data)"
    });
    
    七、请求方式和ajax请求?
    1、ajax发送请求
    2、a、link标签的href发送请求
    3、img、script、iframe的src属性发送请求
    4、表单submit发送请求
    AJAX请求 是与服务器交换数据并更新部分网页的技术。
    HTTP请求 是与服务器交换数据并更新全部网页的技术。 
    
    八、form标签的属性
    1、<form> 标签的 enctype 属性
    (1)application/x-www-form-urlencoded 在发送前编码所有字符(默认)
    (2)multipart/form-data 不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。
    (3)text/plain 空格转换为 "+" 加号,但不对特殊字符编码。
    2、<form> 标签的 action 属性
    (1)必需的 action 属性规定当提交表单时,向何处发送表单数据。
    3、<form> 标签的 name 属性
    (1)name 属性规定表单的名称。
    4、<input> 标签的 type 属性
    (1)为submit时,定义提交按钮。提交按钮会把表单数据发送到服务器。
    5、FormData将仅使用具有name属性的输入字段。 
    
    九、cookie
    1、cookie的作用
    (1)http是一种无状态的协议,服务器不能通过它区分向它发出请求的不同客户;
    (2)cookie可以在前后端进行用户的身份认证,标记用户。
    (3)服务端的解决办法是(简):服务端返给客户端响应头Set-Cookie,客户端接收到这个响应后,此后发送的每一个请求,浏览器都会自动带上Cookie请求头,
    (4)服务端的解决办法是(繁):向客户端种植cookie,并在服务端通过session去管理cookie。当需要记住用户时,比如说登录,在服务端会设置一个响应头Set-Cookie,返回给客户端,例如:Set-Cookie:SESSIONID=12345678;客户端接收到这个响应后,此后发送的每一个请求浏览器都会自动带上Cookie请求头,对应内容是Cookie:SESSIONID=12345678。在服务端内存中存有session,将客户端发送的请求中的cookie值与内存中的session进行对比,就可以识别这个客户端了。
    (5)种cookie的用途,A便于后端判断前端是否已经登陆,B便于后端判断前端登陆是否超时。如果未登录,那么返给前端相应的状态码,前端跳转到登陆页;如果登录已超时,那么重置cookie并返给前端相应的状态码,前端跳转到登陆页。
    2、Cookie的使用
    (1)创建cookie:document.cookie = "username=John Doe; expires=Sun, 31 Dec 2017 12:00:00 UTC";
    (2)读取cookie:var x = document.cookie;
    (3)删除cookie:document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
    
    十、localStorage、sessionStorage
    1、localStorage,永久可用
    2、sessionStorage,页面会话期间可用
    3、localStorage和sessionStorage的方法,以前者为例
    (1)localStorage.setItem (key, value)保存数据,以键值对的方式在浏览器储存信息。
    (2)localStorage.getItem (key) 获取数据,将键传入,即可获取到浏览器对应的value值。
    (3)localStorage.removeItem (key)删除单个数据,根据键移除浏览器对应的信息。
     
    十一、DOM元素的增删改查
    1、增加:appendChild、insertBefore、setAttribute
    2、删除:removeChild
    3、改变:replaceChild
    4、查找:getElementById、getElementsByTagName、getElementsByClassName、querySelector、querySelectorAll
    
    十二、算法知识 
    1、查找算法:
    通过和文件中的关键字进行比较来实现的,都采用平均查找长度来衡量算法的优劣。那么能否有一种方法,不必进行与关键字的比较而达到查找的目的,这样平均查找长度就为0。哈希查找的基本思想是:通过对给定值作某种运算,直接求得(((关键字等于给定值的)记录)在文件中的)位置。
    2、八种数据结构:
    数组、栈、队列、链表、集合、字典、树、图(一组由边连接的顶点)!以数组作为数组元素的数组,叫做二维数组,又叫做矩阵。行数、列数相等的矩阵称为方阵。元素以主对角线为对称轴对应相等的方阵叫做对称矩阵。主对角线外都是零元素的方阵叫做对角矩阵。将矩阵的行列互换得到的新矩阵称为转置矩阵。存放图顶点间关系的矩阵叫做邻接矩阵。
    3、树与二叉树:
    由有限节点组成,具有层级关系的数据结构叫做树;每个节点最多有两个子节点的树叫做二叉树。
    
    十三、显示屏尺寸
    function displayScreen(inch,width,height){
      //(width*x)的平方+(height*x)的平方=inch的平方,求出x即公比;
      var usual=0;
      if(width===4&&height===3){
          usual=25
      }else if(width===16&&height===9){
          usual=337
      }else if(width===21&&height===9){
          usual=522
      }else if(width===16&&height===10){
          usual=356
      }else{
          console.log('没有"'+width+":"+height+'"的显示屏');
          return
      }
      var radio=Math.sqrt(4*usual*inch*inch)/(2*usual)*2.54;
      var line=(inch*2.54).toFixed(2);
      var singleWidth=(radio*width).toFixed(2);
      var singleHeight=(radio*height).toFixed(2);
      console.log(inch+""+width+":"+height+"的显示屏,其对角线长为"+line+"厘米;宽为"+singleWidth+"厘米;高为"+singleHeight+"厘米");
    }
    for(var i=20;i<51;i++){displayScreen(i,16,9);}
     
    十四、编程绝句
    我国清朝彭端淑曰:天下事有难易乎?为之,则难者亦易矣;不为,则易者亦难矣。吾本史学科班出身,为生计和兴趣计,经多次转行,最终以“必为”之心做了程序员。余自转行程序员以来,别妻、离子、抛清明、弃五一、丧端午、失中秋、沦国庆、陷元旦、缺周六、损周日。天明起床、半夜入睡,四季更替,周而复始,专心致志于公司、心无旁骛于陋室。希冀以勤补拙,技上层楼。个中辛苦,有诗为证:编程艰途如攻山, 拼上老命向上攀; 满身创伤终登顶, 无边群峰在眼前。
    编程其一:目视夕阳缓缓落,心盼技术速速升。周遭高楼依次亮,谁知我在中关村?   
    编程其二:十年之前论古今,誓改人间换乾坤。如今只为生计计,犹落风尘做编程。    
    编程其三:当年悟空五行山,腾云驾雾难施展。而今吾身无负重,苦无神技助冲天。 
    编程其四:编程艰途如攻山,拼上性命向上攀。满身创伤终至顶,还有更高在眼前。         
    
    十五、滚动条破坏布局
    (1)问题:当内容增多,滚动条从无到有时,它的出现挤压了内容宽度,导致原来设计好的布局被破坏。
    (2)原因:滚动条的宽度是计算到内容 content 里的。
    (3)解决思路:增加一个中间层,使得外部容器宽度保持设计宽度,内部元素排列保持不变。
    
    杂、细碎知识
    1、重绘:尺寸和位置没有变化
    2、指针:指针、地址、引用
    3、高阶函数:操作其他函数的函数,比如map、forEach
    4、重载:Java可以为一个函数定义两个定义,只要这两个定义的签名(参数的类型和数量)不同即可。JS没有签名,所以不能重载。
    5、动态添加样式 (1)obj.style.width = '400px'; obj.style.height = '300px';(2)obj.style.cssText = "400px; height:300px;";
    6、函数的调用方式 (1)直接调用;(2)对象调用;(3)new调用;(4)call、apply调用
    7、主要浏览器的内核及其前缀 (1)IE trident -ms- (2)欧朋 presto -o- (3)谷歌 webkit -webkit- (4)火狐 gecko -moz-
    8、后台返回的数据和前端代码都没变,前端根据后台数据渲染的图片有时出现,有时不出现。这是因为,渲染图片区域的宽高设为100%,此前该区域是否已被其它路由返回的数据撑开。
     
  • 相关阅读:
    ServiceStack.Redis之IRedisClient<第三篇>【转】
    Redis常用命令速查 <第二篇>【转】
    Redis 安装与简单示例 <第一篇>【转】
    OKHttp使用简介
    android studio快捷键
    android客户端向java服务端post发送json
    安卓开发--HttpDemo02
    安卓开发--HttpDemo01
    安卓开发--HttpClient
    安卓开发--AsyncTask2
  • 原文地址:https://www.cnblogs.com/gushixianqiancheng/p/11384464.html
Copyright © 2020-2023  润新知