Sending file together with form data via ajax post

前端 未结 3 1807
忘了有多久
忘了有多久 2020-12-05 11:22

I\'m trying to upload a file via ajax together with some fields in a form. However, it doesn\'t work. I get this error.

Undefined Index :- File

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 12:09

    Can you try using FormData():

    $("form#files").submit(function(){
    
        var formData = new FormData($(this)[0]);
    
        $.ajax({
            url: window.location.pathname,
            type: 'POST',
            data: formData,
            async: false,
            success: function (data) {
                alert(data)
            },
            cache: false,
            contentType: false,
            processData: false
        });
    
        return false;
    });
    

    The above is a sample code, but you may use it to modify it.

提交回复
热议问题