2017-02-22 103 views
3

我想在发布之前使用beforeSend函数添加一些数据到我的表单中,但数据未在帖子中显示。我猜测表单在数据被添加之前会被序列化,但这只是一个猜测。在ajax之前添加数据形式

这里是我的jQuery/AJAX:

$.ajax({ 
    type: "POST", 
    url: '@Url.Action("SaveHeaders", "Tally")', 
    //data: { model: @Html.Raw(Json.Encode(@Model)) }, 
    data: $('#myForm').serialize(), 
    beforeSend: function() { 
    var displayIndex = imageIndex+1; 
    $("#images tbody").append("<tr><td class='text-center align-middle'>" + displayIndex + "<input type='hidden' id='SellerGroup_" + imageIndex + "__imageId' class='form-control text-box single-line' name='SellerGroup[" + imageIndex + "].imageId' readonly='readonly' value='" + $('#imageName').val() + "' /><td><input type='text' id='SellerGroup_" + imageIndex + "__majorGroup' class='form-control text-box single-line' name='SellerGroup[" + imageIndex + "].majorGroup' readonly='readonly' value='" + major + "' /></td><td><input type='text' id='SellerGroup_" + imageIndex + "__minorGroup' class='form-control text-box single-line' name='SellerGroup[" + imageIndex + "].minorGroup' readonly='readonly' value='" + minor + "' /></td></tr>"); 
        }, 
        success: function (data) { 
         console.log(data); 
        } 
       }); 

回答

1

之前运行$.ajax(...)代码,尽量把这个:

$('#myForm').append('<input type="hidden" name="whateverName" value="whateverValue" />'); 

,然后才运行代码(与$('#myForm').serialize()方法)。

+1

哈,你说得对。我将beforeSend函数中的代码移动到ajax调用之上,现在它按预期工作!非常感谢! – dmikester1