gpt4 book ai didi

javascript - ajax请求中的表单数据不完整

转载 作者:行者123 更新时间:2023-12-03 11:02:11 26 4
gpt4 key购买 nike

陷入这种情况:
我使用 ajax 上传多个输入字段和图像。使用 FileReader api 将图像编码为 base64 字符串。除了发送编码图像之外,一切似乎都正常。

我的代码(简化):

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);
});

问题:在ajax请求表单中缺少数据属性“image”,但在发布带有数据的对象之前是正确的。

也许 readAsDataURL 函数及其 onload 事件存在问题?

最佳答案

类似这样的事情:

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);
});
}

关于javascript - ajax请求中的表单数据不完整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28035701/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com