简体   繁体   English

jQuery上载文件不适用于Ajax

[英]jQuery upload file not work with ajax

I try to upload file with below simple code , but i get error: 我尝试使用以下简单代码上传文件,但出现错误:

$("#register_to_buy_card").submit(function (event) {
        event.preventDefault();
        var $this = $(this);
        var url = $this.attr('action');
        var form = document.forms.namedItem($this);
        var formdata = new FormData(form);
        $.ajax({
            url: url,
            type: "POST",
            dataType: "json",
            data: formData,
            success: function (data) {

            },
            error: function (data) {

            }
        });
    });

I get this error: 我收到此错误:

TypeError: Argument 1 of FormData.constructor is not an object.
var formdata = new FormData(form);

HTML: HTML:

<form id="register_to_buy_card" enctype="multipart/form-data" accept-charset="UTF-8" action="http://localhost/sample/registerToBuyCard" method="POST">

    <label for="passport">Passport Image</label>
    <input type="file" name="passport">
    <div class="checkbox">
    <button class="btn btn-default" type="submit">Submit</button>

</form>

The error you are getting is because: 您收到的错误是因为:

 var form = document.forms.namedItem($this); 

namedItem expects a string. namedItem需要一个字符串。 You are passing it var $this = $(this); 您正在传递它var $this = $(this); , which is a jQuery object. ,这是一个jQuery对象。

this is already a form object. this已经是一个表单对象。 So change: 所以改变:

  var $this = $(this); var url = $this.attr('action'); var form = document.forms.namedItem($this); var formdata = new FormData(form); 

to

var formdata = new FormData(this);

(Yes, those four lines should be replaced with a single line). (是的,应将这四行替换为一行)。


Then see this other question which covers the issues not directly related to your error message. 然后,查看另一个问题 ,该问题涵盖与错误消息不直接相关的问题。

The issue is the element passed in the FormData is not the form but a jQuery object. 问题是在FormData传递的元素不是表单而是jQuery对象。 You need to put the form which is this in the context. 你需要把它的形式是this的背景下。

You need to update this: 您需要更新此:

var formdata = new FormData(this);

and use : 并使用:

contentType:false,
processData:false,

in the ajax options. 在ajax选项中。


Updated code should be: 更新的代码应为:

$("#register_to_buy_card").submit(function (event) {
    event.preventDefault();
    var url = $(this).attr('action');
    var formdata = new FormData(this);  // <--------update with 'this'
    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: formData,
        contentType:false,   //<-----------required
        processData:false,   //<-----------required
        success: function (data) {

        },
        error: function (data) {

        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM