简体   繁体   English

如何使用 jQuery 从表中以 JSON 格式发布数据

[英]How to post data in JSON format from table using jQuery

I have a table as follows:我有一个表如下:

 <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>

I want after clicking that button it should create a json object conataining all data in table send it to the another url using jquery.我想单击该按钮后,它应该创建一个包含表中所有数据的 json 对象,然后使用 jquery 将其发送到另一个 url。

You can select table rows with data and then use $.fn.map method to extract necessary values and put them in array:您可以选择带有数据的表行,然后使用$.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