如何在“状态”中获取进度状态使用socket.io的datatable列 [英] How to get the progress status in the "status" column of a datatable using socket.io

查看:359
本文介绍了如何在“状态”中获取进度状态使用socket.io的datatable列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以连接到套接字并获取数据。但是我无法显示状态列中的百分比。



我得到这个错误:DataTables警告:表id = DataTables_Table_0 - 第0行请求的未知参数null。有关此错误的更多信息,请参阅

解决方案

让我们来看看这里


DataTables中的每个单元格请求数据,并且当DataTables尝试获取单元格的数据并且无法执行此操作时,它将触发警告,告诉您数据不可用。警告消息是:



DataTables警告:表id = {id} - 请求的未知参数
对于行{{row-index},列{column-index}`其中:



p> {id} 替换为已触发
错误的表的DOM ID {parameter} 是数据参数的名称DataTables是
请求 {row-index} 是DataTables内部行索引
row()。index())。
{column-index} 是列数据索引( column()。index())for已触发错误的
列。数据表1.10.10中列的索引信息是
。所以为了分解它,DataTables有
请求的数据给定的行,code> {parameter} 提供,而
没有数据,或它是空值或未定义的(DataTable不知道,
默认情况下如何显示这些参数 - 见下文,如果您的数据
确实包含这些值)。




您正在收到此警报,因为您将 null 值设置为 mData 属性,当你正在建立你的数据库。 这里描述了当 null 是设置为值:


null - 将为单元格使用sDefaultContent选项(默认为null),因此您需要指定您想要的默认内容 - 通常为空字符串)。这可以在生成的列(例如编辑/删除操作列)上有用。


所以,为了摆脱这个警报,你应该设置一个 sDefaultContent 属性:

  aoColumns:[
{
sTitle:文件名,
mData:null,
sDefaultContent:'',
bSortable:false,
sClass head $
sWidth:55px,
render:function(data,type,row,meta){
if(data.IsDirectory){
return < a href ='#'target ='_ blank'>< i class ='fa fa-folder'>< / i>& nbsp;+ data.Name +< / a> ;
} else {
return< a href ='/+ data.Path +'target ='_ balnk'>< i class ='fa+ getFileIcon(data。 Ext)+'>< / i>& nbsp;+ data.Name +< / a>;
}
}
},

保持我记住,你应该为每一列。



PS:
如果您使用 .emit()要发送数据,你应该传递一个对象作为参数。但是,在提供的代码中,您传递一个json字符串。如果要通过套接字发送字符串,请使用 .send()方法:

  io.of('/ socket_issue')。send('message',JSON.stringify({size:state.total,received:state.received,percent:state.percent,fileName:file_name})); 

但是我建议你传递一个对象:


$ b $发送('message',{size:state.total,received:state.received,percent:state.percent,fileName:($ {code> io.of('/ socket_issue'文件名});

在这种情况下,您不应该使用 JSON.parse(data) code>在前面,因为它不再是一个字符串。更改:

  var percentage = JSON.parse(data).percent; 

To:

 code> var percentage = data.percent; 


I'm able to connect to socket and get the data .But I'm unable to display the percent in the status column.

I'm getting this error : DataTables warning: table id=DataTables_Table_0 - Requested unknown parameter 'null' for row 0. For more information about this error, please see http://datatables.net/tn/4.

How to resolve this issue...

Backend code:

io.of('/socket_issue').on('connection', function (socket) {
        console.log("Socket connected :"+socket.id);

    });

var callback = function(state){
    console.log('received size in bytes', state.received);
    console.log('total size in bytes', state.total);
    console.log('percent', state.percent);

     io.of('/socket_issue').emit('message', JSON.stringify({size: state.total, received: state.received, percent: state.percent, fileName: file_name}));

} 

progress(request('https://nodejs.org/dist/v0.12.7/node-v0.12.7.tar.gz'), {
    throttle:0,   
    delay: 0       
})
.on('progress', callback) 

.pipe(fs.createWriteStream(DOWNLOAD_DIR + file_name))
.on('error', function (err) {
 console.log("error");  
})
.on('close', function (err){
console.log("Download Complete"); 
})

My code in template.html:

 {
     "sTitle": "Status",
      align: 'Center', 
      "mData": null, 
      "bSortable": false, 
      "sClass": "head1", 
      "sWidth": "55px",
      "render": socket.on( 'message',   function (data, type, row, meta) {
          console.log(data);//Here I'm able to get socket data
          var percentage = JSON.parse(data).percent;
          if (data.IsDirectory) {
              return percentage;
          }else{
              return percentage;
          }
       })

  }
  ]   


};
socket.on('disconnect', function(){})

My template.html :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>File Browser</title>
    <link rel="stylesheet" href="/lib/bootstrap.min.css">
    <link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/lib/app.css">
  </head>
  <body>
   <div id="panelDiv">

           <div class="panel-heading">
                   <button type="button" id="butDiv" >Browse</button>
                    <input type="text" name="location" size="35"/>
                   <span class="up">
                    <i class="fa fa-level-up"></i> Up
                   </span> 
           </div>
      <div id="showDiv" class="panel-body">
              <table class="linksholder">
              </table>
      </div>

  </div> 
    <script src="/lib/jquery.min.js"></script>
    <script src="/lib/bootstrap.min.js"></script>
    <script src="/lib/datatable/js/jquery.datatables.min.js"></script>
    <script src="/lib/socket.js"></script>

<script>


        var extensionsMap = {
                      ".zip" : "fa-file-archive-o",         
                      ".gz" : "fa-file-archive-o",         
                      ".bz2" : "fa-file-archive-o",         
                      ".xz" : "fa-file-archive-o",         
                      ".rar" : "fa-file-archive-o",         
                      ".tar" : "fa-file-archive-o",         
                      ".tgz" : "fa-file-archive-o",         
                      ".tbz2" : "fa-file-archive-o",         
                      ".z" : "fa-file-archive-o",         
                      ".7z" : "fa-file-archive-o",         
                      ".mp3" : "fa-file-audio-o",         
                      ".cs" : "fa-file-code-o",         
                      ".c++" : "fa-file-code-o",         
                      ".cpp" : "fa-file-code-o",         
                      ".js" : "fa-file-code-o",         
                      ".xls" : "fa-file-excel-o",         
                      ".xlsx" : "fa-file-excel-o",         
                      ".png" : "fa-file-image-o",         
                      ".jpg" : "fa-file-image-o",         
                      ".jpeg" : "fa-file-image-o",         
                      ".gif" : "fa-file-image-o",         
                      ".mpeg" : "fa-file-movie-o",         
                      ".pdf" : "fa-file-pdf-o",         
                      ".ppt" : "fa-file-powerpoint-o",         
                      ".pptx" : "fa-file-powerpoint-o",         
                      ".txt" : "fa-file-text-o",         
                      ".log" : "fa-file-text-o",         
                      ".doc" : "fa-file-word-o",         
                      ".docx" : "fa-file-word-o",         
                    };

$(document).ready(function(){

        $("#showDiv").hide();

});  

$("#butDiv").click(function(){
        $("#showDiv").show();

 });


  function getFileIcon(ext) {
    return ( ext && extensionsMap[ext.toLowerCase()]) || 'fa-file-o';
  }


var socket = io('http://localhost:8089/socket_issue');
  socket.on('connect', function(){ console.log('connected to socket'); });
  socket.on('error', function(e){ console.log('error' + e); });



  var currentPath = null;
   var options = {
        "bProcessing": true,
        "bServerSide": false,
        "bPaginate": false,
        "bAutoWidth": false,
         "sScrollY":"250px",
      "fnCreatedRow" :  function( nRow, aData, iDataIndex ) {
    if (!aData.IsDirectory) return;
    var path = aData.Path;
    $(nRow).bind("click", function(e){
        $.get('/files?path='+ path).then(function(data){
            table.fnClearTable();
            table.fnAddData(data);
            currentPath = path;
        });


        $.get('/directory?path='+ path).then(function(data){        
            $("input[name='location']").val(data.directory);

         });         
    e.preventDefault();
    });
},


        "aoColumns": [{"sTitle":"File Name", "mData": null, "bSortable": false, "sClass": "head0", "sWidth": "55px",
            "render": function (data, type, row, meta) {
              if (data.IsDirectory) {
                return "<a href='#' target='_blank'><i class='fa fa-folder'></i>&nbsp;"  + data.Name +"</a>";
              } else {
                return "<a href='/" + data.Path + "' target='_balnk'><i class='fa " + getFileIcon(data.Ext) + "'></i>&nbsp;" + data.Name +"</a>";
              }
            }
          },
            {"sTitle":"Date",align: 'Center', "mData": null, "bSortable": false, "sClass": "head1", "sWidth": "55px",
            "render": function (data, type, row, meta) {
              if (data.IsDirectory) {
                 return  data.Date;
             }else{
               return data.Date;

             } 
            }
          },


        {"sTitle":"Status",align: 'Center', "mData": null, "bSortable": false, "sClass": "head1", "sWidth": "55px",
            "render":socket.on( 'message',   function (data, type, row, meta) {

                    console.log(data);
              if (data.IsDirectory) {
                 return "";
             }else{
               return "";

             }
            })

          }
        ]   


     };
    socket.on('disconnect', function(){})

  var table = $(".linksholder").dataTable(options);

  $.get('/files').then(function(data){
      table.fnClearTable();
      table.fnAddData(data);
  });

$.get('/directory').then(function(data){        
    $("input[name='location']").val(data.directory);
   $("#showDiv").hide();
});

$(".up").bind("click", function(e){
    if (!currentPath) return;
    var idx = currentPath.lastIndexOf("/");
    var path =currentPath.substr(0, idx);
    $.get('/files?path='+ path).then(function(data){
        table.fnClearTable();
        table.fnAddData(data);
        currentPath = path;
    });

$.get('/directory?path='+path).then(function(data){
    $("input[name='location']").val(data.directory);

 });

});



</script>
</body>
</html>

My screenshot:

解决方案

Let's take a look here:

Each cell in DataTables requests data, and when DataTables tries to obtain data for a cell and is unable to do so, it will trigger a warning, telling you that data is not available where it was expected to be. The warning message is:

DataTables warning: table id={id} - Requested unknown parameter '{parameter}' for row `{row-index}, column{column-index}`` where:

{id} is replaced with the DOM id of the table that has triggered the error {parameter} is the name of the data parameter DataTables is requesting {row-index} is the DataTables internal row index (row().index()) for the row that has triggered the error. {column-index} is the column data index (column().index()) for the column that has triggered the error. The column index information was added in DataTables 1.10.10. So to break it down, DataTables has requested data for a given row, of the {parameter} provided and there is no data there, or it is null or undefined (DataTables doesn't know, by default how to display these parameters - see below if your data does contain these values).

You are getting this alert, because you are setting null value to mData property when you are building your databale. Here is described what happens when null is set as the value:

null - the sDefaultContent option will be used for the cell (null by default, so you will need to specify the default content you want - typically an empty string). This can be useful on generated columns such as edit / delete action columns.

So, to get rid of this alert you should set a sDefaultContent property:

aoColumns": [
      {
        "sTitle":"File Name", 
        "mData": null, 
        sDefaultContent: '',
        "bSortable": false, 
        "sClass": "head0", 
        "sWidth": "55px",
        "render": function (data, type, row, meta) {
          if (data.IsDirectory) {
            return "<a href='#' target='_blank'><i class='fa fa-folder'></i>&nbsp;"  + data.Name +"</a>";
          } else {
            return "<a href='/" + data.Path + "' target='_balnk'><i class='fa " + getFileIcon(data.Ext) + "'></i>&nbsp;" + data.Name +"</a>";
          }
        }
      },

Keep in mind that you should to it for every column.

PS: If you are using .emit() method to send data, you should pass an object as an argument. However, in the provided code you are passing a json string. if you want to send a string via socket, use .send() method:

io.of('/socket_issue').send('message', JSON.stringify({size: state.total, received: state.received, percent: state.percent, fileName: file_name}));

But I would advise you to pass an object:

io.of('/socket_issue').emit('message', {size: state.total, received: state.received, percent: state.percent, fileName: file_name});

In this case you should not use JSON.parse(data) on the front side, since it is not a string anymore. Change:

 var percentage = JSON.parse(data).percent;

To:

 var percentage = data.percent;

这篇关于如何在“状态”中获取进度状态使用socket.io的datatable列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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