2015-03-02 39 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>