2015-03-02 38 views
0

发布数据我有一个表,如下所示:如何JSON格式从表使用jQuery

<html> 
 
    <head> 
 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
 
<script> 
 
$(document).ready(function(){ 
 
$("button").click(function(){ 
 
    // I'd like a suggestion here 
 
    }); 
 
}); 
 
    </head> 
 
    <body> 
 
    <table> 
 
     <tr><th>Name</th><th>Email</th></tr> 
 
     <tr><td>abc</td><td>[email protected]</td></tr> 
 
     <tr><td>xyz</td><tr><td>[email protected]</td> 
 
    </table> 
 
    <button>click here</button> 
 
    </body> 
 
</html>

我想点击该按钮后,它应该创建一个JSON对象conataining中的所有数据表使用jQuery将它发送到另一个URL。

+0

您需要发送什么样的数据? – SarathSprakash 2015-03-02 10:52:06

+0

改进了格式 – 2015-03-06 21:17:21

回答

1

您可以选择与数据表中的行,然后用$.fn.map方法提取必要的值,并把它们放在数组:

$('button').click(function() { 
 
    
 
    var data = $('table tr:gt(0)').map(function() { 
 
     return { 
 
      name: $(this.cells[0]).text(), 
 
      email: $(this.cells[1]).text() 
 
     }; 
 
    }).get(); 
 
    
 
    alert(JSON.stringify(data, null, 4)) 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
     <th>Name</th> 
 
     <th>Email</th> 
 
    </tr> 
 
    <tr> 
 
     <td>abc</td> 
 
     <td>[email protected]</td> 
 
    </tr> 
 
    <tr> 
 
     <td>xyz</td> 
 
     <td>[email protected]</td> 
 
    </tr>  
 
</table> 
 
<button>click here</button>