开发者

howto "submit" a part of a form using jQuery

I'm got a form laid out like a spreadsheet. When the user leaves a row, I want to submit fields from that row to the server using jQuery Ajax. The page is one large form, so this isn't really a javascript clicking the submit button scenario - the form is huge and I only want to send a small开发者_StackOverflow portion of the content for reasons of speed.

I've got the code written that identifies the row and iterates through the fields in the row. My issue is how to build the dat object in order to submit something comprehensible I can disassemble and store at the server end.

At the moment my code looks like this

var dat=[];
$("#" + finalrow).find("input").each(function () {
    var o = $(this).attr("name");
    var v = $(this).val();
    dat.push({ o: v });
});
$.ajax({
    url: 'UpdateRowAjax',
    dataType: 'json',
    type: 'POST',
    data: dat ,
    success: function (data) {
        renderAjaxResponse(data);
    }
});

The assembling of dat doesn't work at all. So how should I build that dat object in order for it to "look" as much like a form submission as possible.


You can add the elements that contain the data you want to send to a jQuery collection, and then call the serialize method on that object. It will return a parameter string that you can send off to the server.

var params = $("#" + finalrow).find("input").serialize();

$.ajax({
    url: 'UpdateRowAjax',
    type: 'POST',
    data: params ,
    success: function (data) {
        renderAjaxResponse(data);
    }
});


You can use $.param() to serialize a list of elements. For example, in your code:

var dat= $.param($("input", "#finalrow"));
$.ajax({
    url: 'UpdateRowAjax',
    dataType: 'json',
    type: 'POST',
    data: dat ,
    success: function (data) {
        renderAjaxResponse(data);
    }
});

Example of $.param(): http://jsfiddle.net/2nsTr/

serialize() maps to this function, so calling it this way should be slightly more efficient.


$.ajax 'data' parameter expects a map of key/value pairs (or a string), rather than an array of objects. Try this:

var dat = {};
$("#" + finalrow).find("input").each(function () {
    dat[$(this).attr('name')] = $(this).val();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜