weixin_33737134 2016-06-17 14:53 采纳率: 0%
浏览 18

用ajax发送数据表单文件

I use the below code to send data for image file with js and they works great but when I add

 var image = document.getElementById("img_book").files[0];
 var form = new FormData(); 
 form.append("image", image);

I get error with append.

This my code

$("#publish").click(function() {
   var x = event.target.responseText;
   document.getElementById("book_id").setAttribute("value",x);
   var image = document.getElementById("img_book").files[0];
   var form = new FormData(); 
   form.append("image", image);

   var title = document.getElementById("title").value;
   var desc = document.getElementById("desc").value;
   var cat = document.getElementById("cat").value;
   var sub_cat = document.getElementById("sub_cat").value;
   var tags = document.getElementById("tags").value;
   var lang = document.getElementById("lang").value;
   var privacy = document.getElementById("privacy").value;
   var id = document.getElementById("book_id").value;
   //if((title !== "") && (desc !== "") && (cat !== "") && (sub_cat !== "") && (lang !== "") && (privacy !== "")) {
     $.ajax({
       url: "ajax/upload/publish.php",
       method  : "POST",
       data : {'form' : form ,'title' : title,'desc' : desc, 'cat' : cat , 'sub_cat' : sub_cat , 'tags' : tags , 'lang' : lang , 'privacy' : privacy , 'id' : id},
       cache: true,
       success : function(data) {
         if(data.status == 'success'){
          window.location.replace("http://localhost/book/book.php?id=" + id);
        }else if(data.status == 'error'){
          alert("Error on query!");
        }
      }
    });
   //}
 });
  • 写回答

1条回答 默认 最新

  • weixin_33712881 2016-06-17 14:57
    关注

    You have to append all the parameters to the formdata object, or more easily pass the form containing the data to the from data constructor.

    Then pass the formdata object alone in the request, also contentType and processData has to be set to false.

    评论

报告相同问题?