~Onlooker 2011-08-07 18:06 采纳率: 0%
浏览 640
已采纳

如何在 jQuery 中使用 ajax 请求发送 FormData 对象? [重复]

This question already has an answer here:

The XMLHttpRequest Level 2 standard (still a working draft) defines the FormData interface. This interface enables appending File objects to XHR-requests (Ajax-requests).

Btw, this is a new feature - in the past, the "hidden-iframe-trick" was used (read about that in my other question).

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.

This works beautifully in all browsers (again, except IE).

Now, I would like to make this functionality work with 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.

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.


Update:

I've created a "feature ticket" over at jQuery's Bug Tracker. It's here: http://bugs.jquery.com/ticket/9995

I was suggested to use an "Ajax prefilter"...


Update:

First, let me give a demo demonstrating what behavior I would like to achieve.

HTML:

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

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:

multipartformdata

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:

wrongcontenttype

As you can see, the content type is wrong...

</div>

转载于:https://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery

  • 写回答

9条回答 默认 最新

  • Didn"t forge 2011-11-23 14:46
    关注

    I believe you could do it like this :

    var fd = new FormData();    
    fd.append( 'file', input.files[0] );
    
    $.ajax({
      url: 'http://example.com/script.php',
      data: fd,
      processData: false,
      contentType: false,
      type: 'POST',
      success: function(data){
        alert(data);
      }
    });
    

    Setting processData to false lets you prevent jQuery from automatically transforming the data into a query string. See the docs for more info.

    Setting the contentType to false is imperative, since otherwise jQuery will set it incorrectly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型