简体   繁体   English

用ajax发送数据表单文件

[英]send data form file with ajax

I use the below code to send data for image file with js and they works great but when I add 我使用下面的代码通过js发送图像文件的数据,它们工作得很好,但是当我添加时

 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!");
        }
      }
    });
   //}
 });

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. 您必须将所有参数附加到formdata对象,或者更容易地将包含数据的表单传递给from数据构造函数。

Then pass the formdata object alone in the request, also contentType and processData has to be set to false. 然后在请求中单独传递formdata对象,而且contentType和processData也必须设置为false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM