从表中读取数据(HTML,JAVAscript)

时间:2014-07-14 08:48:00

标签: javascript jquery html ajax json

我有这个从服务器接收的表: (用ajax):

    $.each(data, function(i, item) {
        $('#MyTable tbody').append("<tr>"d
             +"<td>" +data[i].A+ "</td><td>" 
             +data[i].B
             +"</td><td><input type='text' value='"
             +data[i].C+"'/></td><td><input type='text' value='"
             + data[i].D+"'/></td>"
             + "</tr>");
        });

C和D是编辑文本,用户可以更改。在用户更改之后,我想从表中“获取”所有新数据,并通过带有JSON的ajax发送它。 如何将数据读取为JSON?

我开始写一个,但我坚持:

function saveNewData(){

    var newData= ...
$.ajax({
    type: "GET",
    url: "save",
    dataType: "json",
    data: { 
    newData: newData},
    contentType : "application/json; charset=utf-8",
    success : function(data) {
    ...
    },
    error : function(jqXHR, textStatus, errorThrown) {
        location.reload(true);
    }
    }); 
}

谢谢

3 个答案:

答案 0 :(得分:1)

尝试这样的事情,

function getUserData()
{
    var newData = new Array();
    $.each($('#MyTable tbody tr'),function(key,val){
        var inputF = $(this).find("input[type=text]");          
        var fileldValues = {};
        fileldValues['c'] = $(inputF[0]).val();
        fileldValues['d'] = $(inputF[1]).val();

        //if you want to add A and B, then add followings as well
        fileldValues['a'] = $($(this).children()[0]).text();
        fileldValues['b'] = $($(this).children()[1]).text();
        newData.push(fileldValues);
    });
    return JSON.stringify(newData);
}

function saveNewData(){

var newData = getUserData();
$.ajax({
    type: "GET",
    url: "save",
    dataType: "json",
    data: { 
    newData: newData},
    contentType : "application/json; charset=utf-8",
    success : function(data) {
    ...
    },
    error : function(jqXHR, textStatus, errorThrown) {
        location.reload(true);
    }
}); 
}

答案 1 :(得分:1)

http://jsfiddle.net/yGXYh/1/

基于尼山回答的小型演示:

var newData = new Array();
$.each($('#MyTable tbody tr'), function (key, val) {
    var inputF = $(this).find("input[type=text]");
    var fileldValues = {};
    fileldValues['c'] = $(inputF[0]).val();
    fileldValues['d'] = $(inputF[1]).val();
    newData.push(fileldValues);
});
alert(JSON.stringify(newData));

答案 2 :(得分:1)

使用jquery on事件绑定
尝试这样的事情。 Fiddler Demo

$('#MyTable').on('keyup', 'tr', function(){
    var $this = $(this);
    var dataA = $this.find('td:nth-child(1)').text() // to get the value of A
    var dataB = $this.find('td:nth-child(2)').text() // to get the value of B
    var dataC = $this.find('td:nth-child(3)').find('input').val() // to get the value of C
    var dataD = $this.find('td:nth-child(4)').find('input').val() // to get the Valur of D

    // $.ajax POST to the server form here 
    //  this way you only posting one row to the server at the time

});

我没有做到这一点我会使用数据绑定libarray,例如KnockoutjsAngularJS