2017-02-22 101 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