formData()在追加数据后没有给出数据
问题描述:
第4行给出了表单元素,但第5行在这里没有提供任何内容。我该怎么办?formData()在追加数据后没有给出数据
$('#btnSave').click(function() {
var form = $("#myForm");
var formData = new FormData($(form)[0]);
console.log(form);//this gives form elements
console.log(formData);// but this gives nothing
var url = '<?php echo base_url() ?>' + 'product/add';
$.ajax({
type : 'post',
url : url,
processData: false,
contentType: false,
data: formData,
success: function (response) {
if (response){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
$('.alert-success').html('Record Added').fadeIn().delay(4000).fadeOut('slow');
} else {
alert('Error');
}
},
error: function() {
alert('could not add data');
}
});
});
});
// formData对象没有附加任何东西。任何解决方案,请
答
请尝试下面的代码,并在ajax代码中做一些更改。在代码中添加以下参数。
过程数据:假的,
的contentType:假的,
并添加var formData = new FormData($("#formID")[0]);
线阿贾克斯开始之前。
或者检查以下代码并根据您的代码进行更改。
$('#btnSave').click(function (event) {
var form = $("#myForm");
var formData = new FormData($(form)[0]);;
var url = '<?php echo base_url() ?>' + 'product/add';
if($('#picture').val()==''){
alert("please select the file");
} else{
$.ajax({
type: 'ajax',
data: formData,
url: url,
method: 'POST',
processData: false,
contentType: false,
success: function (response) {
if (response) {
$('#myModal').modal('hide');
$('#myForm')[0].reset();
$('.alert-success').html('Record Added').fadeIn().delay(4000).fadeOut('slow');
setTimeout(function() {// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 1);
} else {
alert('Error');
}
},
error: function() {
alert('could not add data');
}
});
}
});
});
答
在你的代码中有一个以上的错误,在这里我有我正在使用AJAX代码
var form=document.getElementById('form_id');
var fdata=new FormData(form);
$.ajax({
type: "POST",
url: 'Your_url',
dataType: 'json',
data:fdata,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function (data) {
//Do something on response
},
complete: function() {
}
});
这里你的错误是您使用type: "ajax"
未写,因为正确的方式您必须指定数据传递方法POST或GET,
代码中的第二个错误是,您在代码的第三行完成了两个分号(;),所以这就是javascript无法正常工作的原因。
我希望这会对你有用。
谢谢@pankaj但我仍然有这个问题。再次查看这个plz –
你是否正确地检查了我的代码? –
只保留我在代码中添加的东西,并相应地添加代码 –