将jquery datatable数据转换为json [英] convert jquery datatable data as json

查看:85
本文介绍了将jquery datatable数据转换为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery数据表.我有一个如下表,

I am using jquery data table. I have a table like below,

<table id="employees">
  <thead>
     <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Email</th>
        <th>Phone</th>
      </tr>
    </thead>
   <tbody>
      <tr>
           <td>1</td>
           <td>Karthik</td>
           <td>Kk@gmail.com</td>
           <td>1234</td>
       </tr>
       <tr>
           <td>1</td>
           <td>Karthik</td>
           <td>Kk@gmail.com</td>
           <td>1234</td>
       </tr>
     </tbody>
</table>

我正在将表转换为$('#employees').DataTable()

我想将我的jquery数据表转换为json格式. 请帮助我将其转换为

I want to convert my jquery datatable as json format. Please help me to convert this as

[{"Id":"1", "Name":"Karthik","Email":"kk@gmail.com","Phone":"1234"}]

推荐答案

首先需要获取列值:

var heads = [];
$("thead").find("th").each(function () {
  heads.push($(this).text().trim());
});

这将为您提供:

["Id", "Name", "Email", "Phone"]

使用此方法,我们可以在每一行中循环并获取值:

Using this we can loop in each row and get the values:

var rows = [];
$("tbody tr").each(function () {
  cur = {};
  $(this).find("td").each(function(i, v) {
    cur[heads[i]] = $(this).text().trim();
  });
  rows.push(cur);
  cur = {};
});

所以最终您将拥有:

var heads = [];
$("thead").find("th").each(function () {
  heads.push($(this).text().trim());
});
var rows = [];
$("tbody tr").each(function () {
  cur = {};
  $(this).find("td").each(function(i, v) {
    cur[heads[i]] = $(this).text().trim();
  });
  rows.push(cur);
  cur = {};
});

<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<table id="employees">
  <thead>
    <tr>
      <th>Id</th>
      <th>Name</th>
      <th>Email</th>
      <th>Phone</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Karthik</td>
      <td>Kk@gmail.com</td>
      <td>1234</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Praveen</td>
      <td>pp@gmail.com</td>
      <td>5678</td>
    </tr>
  </tbody>
</table>

预览:

输出: http://jsbin.com/kuhuzivadi/编辑吗?html,js,控制台,输出

Output: http://jsbin.com/kuhuzivadi/edit?html,js,console,output

这篇关于将jquery datatable数据转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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