我无法通过ajax上传图片,每当我点击提交按钮时,它总是会重定向到页面,而且数据也没有添加到数据库中。
形式
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>" id="ImageUploadForm" enctype="multipart/form-data">
<input type="text" name="caption" id="caption">
<input type="file" name="image" id="ImageBrowse"/>
<input type="submit" class="btn btn-success" value="Save" />
</form>
AJAX
$(document).ready(function (e) {
$("#imageUploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "<?php echo base_url();?>adminpromisess/addgal",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data) {
alert(data);
//$("#gallery-form").load(".gallery-form");
},
error: function() {
}
});
}));
});
将数据添加到数据库功能(控制器)
public function addgal(){
$caption = $this->input->post('caption');
$promises = 00;
$description = $this->input->post('description');
$image = $_FILES['image']['name'];
if(move_uploaded_file($_FILES['image']['tmp_name'], 'assets/img/upload/promises_image/'.$image)){
$data = array(
'caption' => $caption,
'promises' => $promises,
'gal_desc' => $description,
'image' => $image
);
$result = $this->adminpromisesmodel->addGallery($data);
}else{
echo "Fail to upload file";
die();
}
}
注意:保存数据库的模型(查询)是正确的,所以我没有发布它
答案 0 :(得分:1)
试试这个
$('#imageUploadForm').on('submit', function(ev){
ev.preventDefault();
var forms = document.querySelector('form#imageUploadForm');
var request = new XMLHttpRequest();
var formDatas = new FormData(forms);
request.open('post','yourControllerFunction');
request.send(formDatas);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
//Request was OK show success message
} else {
// Request not OK, show error message
}
}
});
在你的控制器动作中(它是一个cakephp代码)
if($this->request->is('post')){
$data = $this->request->data;
echo "<pre>",print_r($data),"</pre>";
//You should be able to see file data in this array
}
您可以像控制器上的直接表单提交一样处理它
答案 1 :(得分:0)
ImageUploadForm
!= imageUploadForm
修复导致dead code(表单标记)运行的拼写错误并且事情应该按预期工作。 由于该问题,您的浏览器,开发工具,网络选项卡应该显示POST而不是XHR。