[英]AJAX post sending data serialize and image data
I have a problem in post request in AJAX submitting form serialize and my image data array.我在 AJAX 提交表单序列化和我的图像数据数组中发布请求时遇到问题。 How can i do this?
我怎样才能做到这一点?
Here is my code:这是我的代码:
I want to send this data:我想发送这个数据:
var Imagedata = new FormData();
jQuery.each(jQuery('#addfiles')[0].files, function(i, file) {
data.append('file-'+i, file);
});
and和
$("#editProd").serialize()
Here is what I did: data: $("#editProd").serialize()+Imagedata,
这是我所做的:
data: $("#editProd").serialize()+Imagedata,
I have this as fullcode :我有这个作为 fullcode :
function ProductAjax(e) {
e.preventDefault();
var Imagedata = new FormData();
jQuery.each(jQuery('#addfiles')[0].files, function(i, file) {
data.append('file-'+i, file);
});
$.ajax({
url: "{{ route('admin.editProduct') }}",
type: "POST",
data: $("#editProd").serialize()+Imagedata,
dataType: "JSON",
success: function(data) {
if($.isEmptyObject(data.error)){
$('.print-error-msg-addcat').removeClass('alert alert-danger');
$('.print-error-msg-addcat').addClass('alert alert-success');
$('.print-error-msg-addcat').find("ul").html('');
$('.print-error-msg-addcat').css('display','block');
$(".print-error-msg-addcat ul").append('<li class="tick">'+data.success+'</li>');
$('#frmAddcategory')[0].reset();
location.reload();
}else{
printErrorMsgEditprod(data.error);
}
}
});
}
Am I doing right?我做得对吗? Any suggestions?
有什么建议?
Look at the code and comments below:看看下面的代码和注释:
function ProductAjax(e) {
e.preventDefault();
var formData = new FormData($("#editProd")[0]); //assuming this object is a form element.
//the FormData object allows a form element to be passed to the constructor. The new instance
//will have all the form input fields already appended.
//if not a form element you need to append every input seperately using jQuery.serializeArray
jQuery.each(jQuery('#addfiles')[0].files, function(i, file) {
formData.append('file-'+i, file);
});
$.ajax({
url: "{{ route('admin.editProduct') }}",
type: "POST",
data: formData, //send the formData object containing all the form input.
dataType: "JSON",
success: function(data) {
if($.isEmptyObject(data.error)){
$('.print-error-msg-addcat').removeClass('alert alert-danger');
$('.print-error-msg-addcat').addClass('alert alert-success');
$('.print-error-msg-addcat').find("ul").html('');
$('.print-error-msg-addcat').css('display','block');
$(".print-error-msg-addcat ul").append('<li class="tick">'+data.success+'</li>');
$('#frmAddcategory')[0].reset();
location.reload();
}else{
printErrorMsgEditprod(data.error);
}
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.