ajax 表单数据:非法调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16501524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 11:01:06  来源:igfitidea点击:

ajax formdata : Illegal invocation

ajaxfile

提问by darkiron

I try to make ajax script for upload for Symfony 2. Chrome returns this error:

我尝试为 Symfony 2 制作用于上传的 ajax 脚本。Chrome 返回此错误:

Uncaught TypeError: Illegal invocation jquery.min.js:4

未捕获的类型错误:非法调用 jquery.min.js:4

I think it's due to the FormDataobject not correctly constructed (I try the script with .serialized():

我认为这是由于FormData对象构造不正确(我尝试使用以下脚本.serialized()

$(document).ready(function() {
  $('#formImage').submit(function(event) {
    event.preventDefault();
    // appel Ajax
    alert("ajax");

    var input = document.getElementById("rasta_blogbundle_imagetype_file");
    console.log(input); 
    var formdata = false;  

    if (window.FormData) {  
        formdata = new FormData();
        console.log('formdata initialized ...');  
    }
    else{
        console.log('formdata not supported');
    }

    formdata.append('name',$('#rasta_blogbundle_imagetype_name').val());
    console.log(formdata);
    formdata.append('file',input);
    formdata.append('_token',$('#rasta_blogbundle_imagetype__token').val());
    console.log(formdata);    
    //alert(DATA);

    if (formdata){  
        $.ajax({
            url: $(this).attr('action'), // le nom du fichier indiqué dans le formulaire
            type: $(this).attr('method'), // la méthode indiquée dans le formulaire (get ou post)
            cache: false,
            //data : $(this).serialize(),
            data: formdata ,
            success: function(data) { // je récupère la réponse du fichier PHP
                $('#myModal').html(data);
                console.log('ok');
            }        
            //return false; //
        }); 
    }
  });
});

回答by djangonaut

jQuery tries to transform your FormData object to a string, add this to your $.ajax call:

jQuery 尝试将您的 FormData 对象转换为字符串,将其添加到您的 $.ajax 调用中:

processData: false,
contentType: false

回答by user889030

it occurs sometime when jquery internally not serialize data correctly data to fix it add this.

它发生在 jquery 内部没有正确序列化数据以修复它添加此数据的某个时候。

cache : false,
dataType    : 'json',
processData : false,