JQuery1.8.0: Sending files from forms via AJAX

早过忘川 提交于 2019-12-13 06:15:50

问题


I develop with CakePHP and initially thought this problem was Cake-related; it wasn't. I've re-written the question to make the answer I received more widely applicable

I have a form

  <form action"">
      <fieldset> 
      <!---- bunch of fields----->
      <input type="file" name="data[Upload][file]" id="UploadFile">
      <button id="ajaxUploadSubmit"> Submit </button>
      </fieldset>
  </form>

And the submit function I've written looks like:

$( "#ajaxUploadSubmit" ).click(function() {
                $.ajax({
                    url:"uploads/add",
                    data: $( "#UploadsAddForm" ).serialize()
                }).done(function(responseText) {
                    alert(responseText);
                  })
                 .fail(function() {
                     alert('failxors');
                  })
                });

But this line returns an empty array: $this->request->data.


回答1:


I think you are not stopping the form to submit:

$( "#ajaxUploadSubmit" ).click(function(e) {
      e.preventDefault();

Instead of click try submit:

try changing this:

$( "#ajaxUploadSubmit" ).click(function() {

to this one:

$(".form").submit(function(e) {
    e.preventDefault();



回答2:


I'm only adding this answer so this question can be marked as answered; in fact thaJeztah answered this in the 3rd comment of Jai's answer: the problem, in this case, was that I should have been using FormData() instead of Serialize() as seen here: how to do file upload using jquery serialization



来源:https://stackoverflow.com/questions/15506855/jquery1-8-0-sending-files-from-forms-via-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!