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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化