且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将JSON数据表数据以JSON格式发布到服务器

更新时间:2023-09-11 23:03:34

如果您只想收集列名并将其用作JSON中的属性名,则可以通过以下方式构建列名数组:>

If you just want to collect the column names and use them as property names in the JSON, then you can build an array of column names this way :

var fieldNames =  [], json = []
table.settings().columns()[0].forEach(function(index) {
  fieldNames.push($(table.column(index).header()).text())  
})

我正在使用text()过滤掉所有HTML.然后执行上述操作,但改为遍历每一行,并使用收集的fieldNames:

I am using text() to filter out any HTML. Then do as above but iterate over each row instead, and construct an object literal (JSON item) for each row using the collected fieldNames :

table.rows().data().toArray().forEach(function(row) {
  var item = {}
  row.forEach(function(content, index) {
     item[fieldNames[index]] = content
  })
  json.push(item)
})  

现在您有了一个有效的JSON,您可以stringify并将其发送到服务器.

Now you have a valid JSON you can stringify and send to the server.

小样本演示-> http://jsfiddle.net/5j9wgorj/

Small sample demo -> http://jsfiddle.net/5j9wgorj/

请注意,这仅是示例.如果您有更大的数据集,则应避免使用forEach,而应使用for -loops.同样,也不需要盲目地重建标题名称的数组,因为您(开发人员)既知道列名,又希望事先将属性命名为什么.

Note that this is just an example. If you have larger datasets you should avoid forEach and use for-loops instead. Also there should be no need for blindly rebuilding an array of header names since you, the developer, know both column names and what you want the properties to be named as beforehand.

使用最终的解决方案进行更新.如果dataTable本身已准备好使用JSON,则可以避免由于构建JSON而产生的扭曲.定义columns部分:

Update with the solution it ended up to be. The contortions with building a JSON can be avoided if the dataTable itself is prepared for using JSON. Define a columns section :

var table = $('#example').DataTable({
  columns : [
    {  data : 'myField' }
  ]
})

并以JSON/文字形式插入新行:

And insert new rows as JSON / literals :

table.row.add({ myField: 'some value' }).draw()

现在

JSON.stringify( table.rows().data().toArray() )

将返回可以传递到服务器脚本的有效JSON字符串.

Will return a valid JSON string that can be passed to the serverscript.

演示-> http://jsfiddle.net/d07f6uvf/

demo -> http://jsfiddle.net/d07f6uvf/