简体   繁体   English

Ajax请求中的表单数据不完整

[英]Incomplete Form Data in ajax request

Stucked in this situation: 卡在这种情况下:
I upload several inputs fields and images using ajax. 我使用ajax上传了几个输入字段和图像。 Images are encoded to base64 string with FileReader api. 使用FileReader API将图像编码为base64字符串。 Everything seems to work except sending encoded images. 除了发送编码的图像,一切似乎都可以正常工作。

My code (simplified): 我的代码(简体):

var groups = {},
    objects = {};
objects["name"] = {},
objects["group"] = {};
objects["image"] = {};

var objectCount = $(".layout-object").length;
$(".layout-object").each(function(i,v) {
   var k = objectCount-i;
   objects["name"][i] = $(v).val();
   objects["group"][i] = $("#set-object-dropdown-"+k).val();

   // get an image
   var file = document.getElementById('image-'+k).files[0];

   var reader = new FileReader();
   reader.onload = function(event) {  
      objects["image"][i] = event.target.result; // get image in base64
   };
   reader.readAsDataURL(file);
});             

$(".layout-group").each(function(i,v) {
    groups[i] = $(v).val();
});

// prepare object for ajax request...
var data = {
    name: $("#name").val(),
    groups: groups,
    objects: objects
};

// console log shows all data correctly in place = in objects there is a propery "image"...
console.log(data);

// sending ajax POST request
var posting = $.post( location.href, { data: data } );
posting.done(function(response){
        console.log(response);
});

Issue: in ajax request form data property "image" is missing, but before posting object with data is correct. 问题:在ajax请求表单中缺少数据属性“ image”,但是在发布带有数据的对象之前是正确的。

Maybe is there a problem with readAsDataURL function and its onload event? 也许readAsDataURL函数及其onload事件存在问题?

Something like this: 像这样:

reader.onload = function(event) {  
  objects["image"][i] = event.target.result; // get image in base64
  if (k == 1) //when the last object is iterated and it's image is set:
  {
     fireAjax();
  }

}; };

function fireAjax(){
    // sending ajax POST request
    var posting = $.post( location.href, { data: data } );
    posting.done(function(response){
            console.log(response);
    });
}

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

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