php - 使用 AJAX 进行 jquery 验证后的图像上传
问题描述
我正在使用 CodeIgniter。我正在尝试在 jquery 验证后使用 AJAX 上传图像,但它不起作用。如果字段为空,则 Jquery 验证正在工作。填写完所有字段并单击提交按钮后,我的页面刷新了。它不是在调用控制器。
你能帮帮我吗?
$("#primary").validate({
errorElement: 'div',
rules: {
first_name: {
required: true,
alphabets: true,
minlength: 3
},
last_name: {
alphabets: true
},
profile_pic: {
extension: "png|jpeg|jpg|gif"
},
},
messages: {
profile_pic: {
extension: "Only PNG , JPEG , JPG, GIF File Allowed",
},
},
submitHandler: function(form)
{
var formData = new FormData(this);
$.ajax({
url: baseUrl + "/AddMember/addMembers",
type: 'POST',
//data: $('#primary').serialize(),
data:formData,
dataType: 'json',
success: function(data)
{
if (data.error == "true")
{
//success message
}
else {
//error message
}
}
});
}
});
控制器代码
$config=['upload_path' =>'./uploads/images',
'allowed_types' =>'gif|jpg|png|jpeg',
'file_name' =>uniqid().time().date("dmy")
];
if ($this->upload->do_upload('profile_pic'))
{
$profile_pic_set = $this->upload->data('file_name');
}
else{$profile_pic_set = "";//set empty value if user not uploading any image
}
$this->load->library('upload', $config);
$data = array(
'first_name' => trim($this->input->post('first_name')),
'last_name' => trim($this->input->post('last_name')),
'profile_pic' => $profile_pic_set
);
print_r($data); //here I am getting profile_pic empty.
html
<?php echo form_open_multipart('','id="primary"'); ?>
<input type="text" name="first_name" id="first_name" class="form-control" placeholder="First Name">
<input type="text" name="last_name" id="last_name" class="form-control" placeholder="Last Name">
<input type="file" name="profile_pic" id="file_upload">
<button type="submit" class="btn btn-primary btn_new">Submit</button>
<?php echo form_close(); ?>
解决方案
TypeError:FormData.constructor 的参数 1 没有实现接口 HTMLFormElement
你的问题在里面FormData(this)
。this
代表验证器本身,而不是表单对象。表单对象由form
传递给submitHandler
.
所以FormData()
应该包含这个form
论点。
另外,需要将 AjaxprocessData
和contentType
参数设置为false
...
submitHandler: function(form){
var formData = new FormData(form);
$.ajax({
url: baseUrl + "/AddMember/addMembers",
type: 'POST',
data: formData,
dataType: 'json',
processData: false,
contentType: false,
....
参考资料:
使用 ajax 发送图像,在 submitHandler 上使用 jquery 验证器
TypeError:在未实现接口 FormData 的对象上调用了“附加”
推荐阅读
- c - printf 转换的正确规则是什么?
- ios - FirebaseUI/PhoneAuth/FirebasePhoneAuthUI/FUICodeField.xib:-1:未能找到或创建描述的执行上下文
- javascript - 堆积条形图比例不一致问题
- angular - 如何仅在休眠中更新 JSON 定义的属性
- clojure - RabbitMQ:客户端未收到客户端启动前发送的消息
- python - DurationField 或 Timedelta
- ios - 如何使用 ApiAi Pod 从 Swift 向 Dialogflow 发送访问令牌
- javascript - 运行js超时的插件
- python - VS Code 和 Python -> 缺少自动完成功能
- python - 如何创建没有索引错误的 folium.chloropleth 地图?