【问题标题】:jQuery / AJAX - send additional data together with file uploadjQuery / AJAX - 与文件上传一起发送附加数据
【发布时间】:2015-09-15 14:14:24
【问题描述】:

我正在使用 jQuery 将文件上传到服务器:

 $.ajax({
    url : 'http://www.example.com',
    dataType : 'json',
    cache : false,
    contentType : false,
    processData : false,
    data : formData, // formData is $('#file').prop('files')[0];
    type : 'post',
    success : function(response) {something}
   });

我想将附加参数与文件一起发送。可能吗?如果是 - 如何?

谢谢!

【问题讨论】:

    标签: javascript jquery ajax file-upload jquery-file-upload


    【解决方案1】:

    要发送其他参数,您只需将其附加到formdata,如下所示:

    var formdata=new FormData();
    formdata.append('simpleFile', $('#file').get('files')[0]); //use get('files')[0]
    formdata.append('someotherparams',someothervalues);//you can append it to formdata with a proper parameter name 
    
    $.ajax({
        url : 'http://www.example.com',
        dataType : 'json',
        cache : false,
        contentType : false,
        processData : false,
        data : formData, //formdata will contain all the other details with a name given to parameters
        type : 'post',
        success : function(response) {something}
    });
    

    【讨论】:

      【解决方案2】:

      试试这个,

      $( "form" ).on( "submit", function( event ) {
         var formData = $( this ).serialize();
          //$.ajax({}) //remaining code here 
      });
      

      【讨论】:

        【解决方案3】:

        您必须使用FormData 对象序列化表单,而不是仅发送文件。

        var formData = new FormData($("form")[0]);
        

        【讨论】:

          猜你喜欢
          • 2014-01-22
          • 2014-10-24
          • 2013-04-05
          • 2015-05-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多