douqie1816 2012-08-20 15:19
浏览 98
已采纳

jQuery循环遍历表并获取元素

i've got some form input elements in an html table like this:

<table>
    <thead>
    ....
    </thead>
    <tr>
        <td><input type="text" name="n_time" id="5030c9261eca0" value="2012" /></td>
        <td><input type="text" name="n_name" id="5030c9261eca0" value="a name" /></td>
        <td><textarea name="n_comment" id="5030c9261eca0">bla</textarea></td>
    </tr>
</table>

now, i need to send this form data using $.post to my PHP processing page which looks something like

if($_POST['data']){
    $array = json_decode($_POST['data']);

}

so i need to get all my form elements and somehow made then into JSON

and this is what i did:

// assume i can get 5030c9261eca0 from my predefined vars...
$my_array = $("#5030c9261eca0").map(function () { return $(this).is("input")?$(this).val():$(this).text(); } );
//now convert
JSON.stringify($my_array);
// the conversion failed with : Uncaught TypeError: Converting circular structure to JSON 

this error poped up:

Uncaught TypeError: Converting circular structure to JSON 

how do i fix this?

also, if i do regluar HTTP post via HTML forms, i can recieve form data like $_POST['n_name'] in PHP if i have a HTML form element with attribute n_name, how can i accomplish the same with the above?

  • 写回答

2条回答 默认 最新

  • dongshandun4363 2012-08-20 15:22
    关注

    First loop through all tr, then loop trought all input,textarea and push gathered values to array.

    var data = [];      
    $('table tr').each(function(){
        var row = {};
        $(this).find('input,textarea').each(function(){
            row[$(this).attr('name')] = $(this).val();
        });
        data.push(row);
    });
    
    // now you can use "data" :)
    

    Example data:

    [0][n_time] = foo
    [0][n_name] = bar
    [0][n_comment] = 123
    [1][n_time] = foo
    [1][n_name] = bar
    [1][n_comment] = 123
    ...
    

    jQuery:

    $.post("test.php", { 'mydata': data } );
    

    PHP:

    foreach($_POST['mydata'] as $row) {
        echo $row['n_name'];
    }
    

    It's good idea to convert it to jQuery function:

    (function( $ ) {
      $.fn.tableData = function() {
        var data = [];      
        $(this).find('tr').each(function(){
            var row = {};
            $(this).find('input,textarea').each(function(){
                row[$(this).attr('name')] = $(this).val();
            });
        });
        return data;
      }
    })( jQuery );
    
    // Usage:
    
    $.post("test.php", { 'mydata': $('table').tableData() } );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏