jQuery动态创建和提交表单

9
我正在尝试通过代码创建并提交表单。以下代码有什么问题?
$('#btnPrintInvoicePerFile').on('click', function (event) {
    event.preventDefault(); //stop link default

    var componentInvoiceId = EberlsComponentInvoiceForm.componentInvoice.Id;
    console.log(componentInvoiceId);

    $('<form>', {
        "id": "getInvoiceImage",
        "html": '<input type="text" id="componentInvoicId" name="componentInvoicId" value="' + componentInvoiceId + '" />',
        "action": window.siteRoot + 'ComponentInvoice/GetInvoiceImage/'
    }).submit();

});

1
你可能想要查看jQuery .post http://api.jquery.com/jQuery.post/。它可能更接近你所寻找的内容。 - Brian Hoover
下面有什么问题吗?我不知道,你遇到了哪些错误?你认为应该发生什么事情却没有发生? - j08691
1个回答

32

先尝试将表单附加到 body 元素上:

$('<form>', {
    "id": "getInvoiceImage",
    "html": '<input type="text" id="componentInvoicId" name="componentInvoicId" value="' + componentInvoiceId + '" />',
    "action": window.siteRoot + 'ComponentInvoice/GetInvoiceImage/'
}).appendTo(document.body).submit();

啊,必须先将其附加到body上。这个方法可行!提交后是否值得从body中删除? - Mark
2
@Mark 不行,因为页面会卸载,然后表单就被提交了。 - Corneliu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接