如何触发我的 jquery 表单提交

How to trigger my jquery form submit

本文关键字:表单提交 jquery 我的 何触发      更新时间:2023-09-26

现在表单正在提交,但它使用的是默认网址,我希望它在我的javascript中使用表单提交事件,以便它通过.ajaxSubmit()选项。

这是javascript。

$('#selectedFile').change(function() {
    var id = $('#selectedFile').data('id');
    var options = {
        target: '#output',    
        beforeSubmit: showRequest,  
        success: showResponse,  
        url: '/ManageSpaces/UploadImage',
        data: { id: id },
        type:      'post'        
       
    };
    $("#imageform").trigger('submit'); // I want this to trigger the submit below! Not the default form submit.
    
    $('#imageform').submit(function () {
         
        $(this).ajaxSubmit(options);
        
        return false;
    });
});

<form id="imageform" enctype="multipart/form-data">
            <input type="file" id="selectedFile" style="display: none;" data-id='@Model.YogaSpaceId' />
            <input type="button" value="Add Photos" class="btn" id="pictureupload" />
        </form>

操作方法

[HttpPost]
    public ActionResult UploadImage(int id, HttpPostedFileBase image)
    {
        //do some stuff to save the image
        return Json("Saved");
    }

您在注册提交处理程序之前触发提交,在您的情况下,一种选择是直接在更改处理程序中调用ajaxSubmit,而无需使用提交处理程序,如下所示。

$('#selectedFile').change(function () {
    var id = $('#selectedFile').data('id');
    var options = {
        target: '#output',
        beforeSubmit: showRequest,
        success: showResponse,
        url: '/ManageSpaces/UploadImage',
        data: {
            id: id
        },
        type: 'post'
    };
    $('#imageform').ajaxSubmit(options);
});

另一种选择是在更改处理程序之外注册提交处理程序,如下所示,并在更改处理程序中触发提交

$('#selectedFile').change(function () {
    $("#imageform").trigger('submit'); // I want this to trigger the submit below! Not the default form submit.
});
$('#imageform').submit(function () {
    var id = $('#selectedFile').data('id');
    var options = {
        target: '#output',
        beforeSubmit: showRequest,
        success: showResponse,
        url: '/ManageSpaces/UploadImage',
        data: {
            id: id
        },
        type: 'post'
    };
    $(this).ajaxSubmit(options);
    return false;
});