簡體   English   中英

如何使用 jQuery 從表中以 JSON 格式發布數據

[英]How to post data in JSON format from table using 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>abc@gmail.com</td></tr> <tr><td>xyz</td><tr><td>xyz@gmail.com</td> </table> <button>click here</button> </body> </html>

我想單擊該按鈕后,它應該創建一個包含表中所有數據的 json 對象,然后使用 jquery 將其發送到另一個 url。

您可以選擇帶有數據的表行,然后使用$.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>abc@gmail.com</td> </tr> <tr> <td>xyz</td> <td>xyz@gmail.com</td> </tr> </table> <button>click here</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM