如何合并两个Ajax调用,以便它们使用formData API传递表单输入数据以及表单图像数据?
查看Ajax调用:
$("#submitbmsymptom").click(function(h){
h.preventDefault();
var radioValue;
$('#radio1, #radio2, #radio3, #radio4').each(function(){
if($(this).is(':checked')){
radioValue = $(this).val();
}
});
console.log(radioValue +
$("#bmdate").val() +
$("#bmtime").val() +
$("#bmscale").val() +
$("#bmpainlevel").val() +
$("#bmobs").val()
);
$.ajax({
url:'urllocation',
method: 'POST',
data:{
bmdate_data : $("#bmdate").val(),
bmtime_data : $("#bmtime").val(),
bmscale_data : $("#bmscale").val(),
bmcontents_data : radioValue,
bmpainlevel_data : $("#bmpainlevel").val(),
bmobs_data : $("#bmobs").val(),
},
}
).done(function(regresult){
});
})
$("#submitbmsymptom").click(function(h){
h.preventDefault();
var pooPicture = $('input[name=poopic]');
var fileUpload = pooPicture[0].files[0];
var formData = new FormData();
formData.append("file", fileUpload);
$.ajax({
url:'urllocation',
method: 'POST',
data: formData,
processData: false,
contentType: false,
success: function() {
alert("File uploaded");
}
});
})
Controller方法接收数据,将文件保存到服务器,然后使用关联数组将字符串数据和文件名插入数据库:
function bowelmovements(){
$bmuserid = $this->session->userdata('id');
$bmsymptomdate = $this->input->post('bmdate_data');
$bmsymptomtime = $this->input->post('bmtime_data');
$bmsymptomtype = $this->input->post('bmscale_data');
$bmsymptomlocation = $this->input->post('bmcontents_data');
$bmsymptompainlevel = $this->input->post('bmpainlevel_data');
$bmsymptomobs = $this->input->post('bmobs_data');
$config['upload_path'] = APPPATH.'/assets/uploads/';
$config['allowed_types'] = "gif|jpg|png|mp4";
$this->load->library('upload', $config);
if($this->upload->do_upload("file")){
$imageData = $this->upload->data();
$fileName = $imageData[file_name];
$bmdata = array(
'userid' => $bmuserid,
'bmdate' => $bmsymptomdate ,
'bmtime' => $bmsymptomtime,
'bmscale' => $bmsymptomtype,
'bmcontents' => $bmsymptomlocation ,
'bmpainlevel' => $bmsymptompainlevel,
'bmobs' => $bmsymptomobs,
'bmimage' => $fileName
);
$insertBM = $this->poomonitormodel->insertBM($bmdata);
}
else{
echo "File not uploaded";
}
}
目前,这仅提交第二个Ajax调用,并仅将文件名插入数据库,但是我需要将这两组数据提交到表中。
感谢。
答案 0 :(得分:0)
在这里,我将你的2个ajax调用浓缩为一个:
$("#submitbmsymptom").click(function(h){
h.preventDefault();
var radioValue;
$('#radio1, #radio2, #radio3, #radio4').each(function(){
if($(this).is(':checked')){
radioValue = $(this).val();
}
});
var pooPicture = $('input[name=poopic]');
var fileUpload = pooPicture[0].files[0];
var formData = new FormData();
formData.append("file", fileUpload);
formData.append("bmdate_data", $("#bmdate").val());
formData.append("bmtime_data", $("#bmtime").val());
formData.append("bmscale_data", $("#bmscale").val());
formData.append("bmcontents_data", radioValue);
formData.append("bmpainlevel_data", $("#bmpainlevel").val());
formData.append("bmobs_data", $("#bmobs").val());
$.ajax({
url:'urllocation',
method: 'POST',
processData: false,
contentType: false,
data: formData,
}).done(function(regresult){
});
});