如何在jQuery中发送带有Ajax请求的FormData对象? [重复]

该文讨论如何在jQuery中使用Ajax发送FormData对象。传统方法遇到问题,如'非法调用'错误。示例代码展示正确做法,但实际应用中内容类型设置不正确。解决方案包括使用Ajax预过滤器和直接通过formData参数传递表单数据。
摘要由CSDN通过智能技术生成

本文翻译自:How to send FormData objects with Ajax-requests in jQuery? [duplicate]

This question already has an answer here: 这个问题已经在这里有了答案:

The XMLHttpRequest Level 2 standard (still a working draft) defines the FormData interface. XMLHttpRequest 2级标准(仍然是工作草案)定义了FormData接口。 This interface enables appending File objects to XHR-requests (Ajax-requests). 此接口允许将File对象附加到XHR请求(Ajax请求)。

Btw, this is a new feature - in the past, the "hidden-iframe-trick" was used (read about that in my other question ). 顺便说一句,这是一个新功能-过去曾使用过“ hidden-iframe-trick”(请在我的另一个问题中阅读 )。

This is how it works (example): 它是这样工作的(示例):

var xhr = new XMLHttpRequest(),
    fd = new FormData();

fd.append( 'file', input.files[0] );
xhr.open( 'POST', 'http://example.com/script.php', true );
xhr.onreadystatechange = handler;
xhr.send( fd );

where input is a <input type="file"> field, and handler is the success-handler for the Ajax-request. 其中input是一个<input type="file">字段,并且handler是Ajax请求的成功处理程序。

This works beautifully in all browsers (again, except IE). 在所有浏览器中(同样,除IE之外),它都能很好地工作。

Now, I would like to make this functionality work with jQuery. 现在,我想使此功能与jQuery一起使用。 I tried this: 我尝试了这个:

var fd = new FormData();    
fd.append( 'file', input.files[0] );

$.post( 'http://example.com/script.php', fd, handler );

Unfortunately, that won't work (an "Illegal invocation" error is thrown - screenshot is here ). 不幸的是,这是行不通的(抛出“非法调用”错误- 屏幕截图在此处 )。 I assume jQuery expects a simple key-value object representing form-field-names / values, and the FormData instance that I'm passing in is apparently incompatible. 我假设jQuery需要一个表示表单字段名称/值的简单键值对象,而我要传递的FormData实例显然不兼容。

Now, since it is possible to pass a FormData instance into xhr.send() , I hope that it is also possible to make it work with jQuery. 现在,由于可以将FormData实例传递给xhr.send() ,所以我希望也可以使其与jQuery一起使用。


Update: 更新:

I've created a "feature ticket" over at jQuery's Bug Tracker. 我已经在jQuery的Bug跟踪器上创建了“功能票”。 It's here: http://bugs.jquery.com/ticket/9995 在这里: http : //bugs.jquery.com/ticket/9995

I was suggested to use an "Ajax prefilter"... 建议我使用“ Ajax预过滤器” ...


Update: 更新:

First, let me give a demo demonstrating what behavior I would like to achieve. 首先,让我做一个演示,演示我想要实现的行为。

HTML: HTML:

<form>
    <input type="file" id="file" name="file">
    <input type="submit">
</form>

JavaScript: JavaScript:

$( 'form' ).submit(function ( e ) {
    var data, xhr;

    data = new FormData();
    data.append( 'file', $( '#file' )[0].files[0] );

    xhr = new XMLHttpRequest();

    xhr.open( 'POST', 'http://hacheck.tel.fer.hr/xml.pl', true );
    xhr.onreadystatechange = function ( response ) {};
    xhr.send( data );

    e.preventDefault();
});

The above code results in this HTTP-request: 上面的代码导致此HTTP请求:

多部分数据

This is what I need - I want that "multipart/form-data" content-type! 这就是我需要的 -我想要“多部分/表单数据”内容类型!


The proposed solution would be like so: 提议的解决方案如下所示:

$( 'form' ).submit(function ( e ) {
    var data;

    data = new FormData();
    data.append( 'file', $( '#file' )[0].files[0] );

    $.ajax({
        url: 'http://hacheck.tel.fer.hr/xml.pl',
        data: data,
        processData: false,
        type: 'POST',
        success: function ( data ) {
            alert( data );
        }
    });

    e.preventDefault();
});

However, this results in: 但是,这导致:

错误的内容类型

As you can see, the content type is wrong... 如您所见,内容类型是错误的...


#1楼

参考:https://stackoom.com/question/TGQu/如何在jQuery中发送带有Ajax请求的FormData对象-重复


#2楼

我发现的最佳文档和示例在此处https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects


#3楼

JavaScript: JavaScript:

function submitForm() {
    var data1 = new FormData($('input[name^="file"]'));
    $.each($('input[name^="file"]')[0].files, function(i, file) {
        data1.append(i, file);
    });

    $.ajax({
        url: "<?php echo base_url() ?>employee/dashboard2/test2",
        type: "POST",
        data: data1,
        enctype: 'multipart/form-data',
        processData: false, // tell jQuery not to process the data
        contentType: false // tell jQuery not to set contentType
    }).done(function(data) {
        console.log("PHP Output:");
        console.log(data);
    });
    return false;
}

PHP: PHP:

public function upload_file() {
    foreach($_FILES as $key) {
        $name = time().$key['name'];
        $path = 'upload/'.$name;
        @move_uploaded_file($key['tmp_name'], $path);
    }
}

#4楼

I do it like this and it's work for me, I hope this will help :) 我这样做,对我有用,希望对您有所帮助:)

   <div id="data">
        <form>
            <input type="file" name="userfile" id="userfile" size="20" />
            <br /><br />
            <input type="button" id="upload" value="upload" />
        </form>
    </div>
  <script>
        $(document).ready(function(){
                $('#upload').click(function(){

                    console.log('upload button clicked!')
                    var fd = new FormData();    
                    fd.append( 'userfile', $('#userfile')[0].files[0]);

                    $.ajax({
                      url: 'upload/do_upload',
                      data: fd,
                      processData: false,
                      contentType: false,
                      type: 'POST',
                      success: function(data){
                        console.log('upload success!')
                        $('#data').empty();
                        $('#data').append(data);

                      }
                    });
                });
        });
    </script>   

#5楼

Instead of - fd.append( 'userfile', $('#userfile')[0].files[0]); 而不是fd.append( 'userfile', $('#userfile')[0].files[0]);

Use - fd.append( 'file', $('#userfile')[0].files[0]); 使用fd.append( 'file', $('#userfile')[0].files[0]);


#6楼

You can send the FormData object in ajax request using the following code, 您可以使用以下代码在ajax请求中发送FormData对象,

$("form#formElement").submit(function(){
    var formData = new FormData($(this)[0]);
});

This is very similar to the accepted answer but an actual answer for the question topic. 这与已接受的答案非常相似,但实际上是针对问题主题的答案。 This will submit the form elements automatically in the FormData and you don't need to manually append the data to FormData variable. 这将自动在FormData中提交表单元素,而您无需手动将数据附加到FormData变量中。

The ajax method looks like this, ajax方法看起来像这样,

$("form#formElement").submit(function(){
    var formData = new FormData($(this)[0]);
    //append some non-form data also
    formData.append('other_data',$("#someInputData").val());
    $.ajax({
        type: "POST",
        url: postDataUrl,
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function(data, textStatus, jqXHR) {
           //process data
        },
        error: function(data, textStatus, jqXHR) {
           //process error msg
        },
});

You can also manually pass the form element inside the FormData object as parameter like this 您也可以像这样手动将FormData对象内的form元素作为参数传递

var formElem = $("#formId");
var formdata = new FormData(form[0]);

Hope it helps. 希望能帮助到你。 ;) ;)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值