duanfei9278 2015-09-07 09:56
浏览 38

PHP AJAX JQuery附件电子邮件[重复]

This question already has an answer here:

Just looking for some advice really. I have a small form on my website which i'm building:

  • Name
  • Email
  • Number
  • CV (attachment)

I have done forms before, however with the added attachment i'm not sure how to go about it.

Im used to using jQuery's serialize function. Is there something similar i can use to post within my Ajax call? I cant seem to find much info on the web..

</div>
  • 写回答

1条回答 默认 最新

  • douxieti6851 2015-09-07 09:59
    关注

    For AJAX requests, you cannot really use .serialize() functions. You need to use FormData(). You can also put a progress bar. We need to check for the support first:

    function supportAjaxUploadWithProgress() {
      return supportFileAPI() && supportAjaxUploadProgressEvents() && supportFormData();
    
      function supportFileAPI() {
        var fi = document.createElement('INPUT');
        fi.type = 'file';
        return 'files' in fi;
      };
    
      function supportAjaxUploadProgressEvents() {
        var xhr = new XMLHttpRequest();
        return !! (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload));
      };
    
      function supportFormData() {
        return !! window.FormData;
      }
    }
    

    The next step is to submit the form using AJAX:

    var form = document.getElementById('form-id');
    var formData = new FormData(form);
    

    You have to have these HTML:

    var form = document.getElementById('the-form');
    form.onsubmit = function() {
      var formData = new FormData(form);
    
      formData.append('file', file);
    
      var xhr = new XMLHttpRequest();
      // Add any event handlers here...
      xhr.open('POST', form.getAttribute('action'), true);
      xhr.send(formData);
    
      return false; // To avoid actual submission of the form
    }
    <form id="the-form" action="/upload/path" enctype="multipart/form-data">
      <input name="file" type="file">
      <input type="submit" value="Upload" />
    </form>

    More info: Ridiculously simple Ajax uploads with FormData.

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line