苦苦挣扎着使用ajax文件上传

时间:2014-03-06 13:07:00

标签: jquery ajax

如果我只是使用序列化表格作为数据,我可以让它工作但是因为我试图包括上传文件也失败了,它什么都没做?

 $(document).ready(function() {  
    $('#advice_submit').click(function(e){
     var formData = new FormData($('form#ask_advice_form')[0]); 
              $.ajax({
              url: 'ajax/ask_advice_ajax.php',
              type:'POST',
              data: formData,
              dataType: 'json',
                success: function(response){
                    $('#success').html(response.question_id+' '+response.user); 
                }, // End of success function of ajax form
                error:function (xhr, ajaxOptions, thrownError){
                alert(thrownError);
             }
        }); // End of ajax call 
     });//close whole function
  });//close whole function

表格

    <form method="post" enctype="multipart/form-data" id="ask_advice_form">
         <input type="text" id="desc" name="desc"  maxlength="50">
         <textarea name="advice_question" id="advice_question"></textarea>
         <input type="file" name="file" id="image" style="border:none">
    <input type="button" name="advice_submit" id="advice_submit" value=""
          class="request_opinion white_submit" >
     </form>

2 个答案:

答案 0 :(得分:1)

您只能将formData发送到请求正文。 我认为这篇文章对您有所帮助:Ajax file upload

答案 1 :(得分:0)

使用此功能......

$(document).ready(function() { 
$("#advice_submit").click( function() {
  var formData = new FormData($('#ask_advice_form')[0]);
     $.ajax({
           url: 'ajax/ask_advice_ajax.php',
           data: formData,
           async: false,
           contentType: false,
           processData: false,
           cache: false,
           type: 'POST',
           success: function(response)
           {
               alert('smeg');
           },
         });    return false;    
    });
});

似乎我错过了这些元素:

async: false,
contentType: false,
processData: false,
cache: false,