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.

    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮