2014-11-06 39 views
-1

这个问题可能是愚蠢的,但由于我是新来的JS和JQuery,我一直在努力完成它。将整个表数据传递给使用jquery的动作方法

我在页面中有一个表格,用户可以编辑单元格值(我正在使用contenteditable属性)。 有一个“全部保存”按钮,单击我想要将表中所有行的当前值发送到服务器端操作方法。

请建议我如何实现这个或更好的方式来实现相同的功能。

+0

您需要将表序列化为[JSON](http://www.json.org/)并将其发送到您的操作。 – 2014-11-06 18:48:49

回答

1

当点击Save All按钮,你可以做这样的事情:

$("#saveAllBtnId").click (function() { 

// read the data from the table using loop 
    $('#myTable > tbody > tr').each(function() { 

    // here retrieve the values from the table cells 
    // Example 
    var cellValue = $(this).... // you need to fill this code as per your table structure 

    // store all the data in an array 
    var mydata = new Array (cellValue, ....); 
    var jsonData = JSON.stringify(mydata); 

    // send the data to backend, e.g. 
    $.post ("back/end/code", { data : jsonData }, function() {}); 

    }); 

}); 
0

非常感谢。这是我想要的。但是,在创建数组时需要稍作修改。下面是工作代码。

 function btnClicked() { 
     // read the data from the table using loop 
     var mydata = []; 
     $('#testTable > tbody > tr').each(function() { 

      // here retrieve the values from the table cells 
      // Example 
      var name = ($(this).find(".name").html()); 
      var age = ($(this).find(".age").html()); 

      var obj = { name: name, age: age }; 

      // store all the data in an array 
      mydata.push(obj); 


     }); 
     var jsonData = JSON.stringify(mydata); 

     // send the data to backend, e.g. 
     //for now adding an alert 
     for (var i = 0 ; i < mydata.length; i++) { 

      alert(mydata[i].name + mydata[i].age); 
     } 
     $.post ("Test/SomeAction", { data : jsonData }, function() {}); 

    }