gpt4 book ai didi

php - 在 codeigniter 中使用 AJAX 上传文件时出错

转载 作者:行者123 更新时间:2023-12-01 07:47:28 24 4
gpt4 key购买 nike

我正在 codeigniter 中制作一个管理面板。我有一个 table 上游戏。它里面有一个图像。我想使用ajax上传该图像。但由于某种原因,图像没有上传,并且发生错误,没有选择文件。

Controller

public function ajax_add() {
$this->_validate();

$config = [
'upload_path' => './assets/game_images/',
'allowed_types' => 'gif|png|jpg|jpeg'
];
$this->load->library('upload', $config);
if ($this->upload->do_upload()) {
$file = $this->upload->data();
$file_name = $file['file_name'];

if ($file_name == '') {
$data['error_string'][] = 'Please upload an image.';
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
} else {
$data['inputerror'][] = 'image';
$data['error_string'][] = $this->upload->display_errors();
$data['status'] = FALSE;
echo json_encode($data);
exit();
}

$data = array(
'title' => $this->input->post('title'),
'iframe' => $this->input->post('iframe'),
'status' => $this->input->post('status'),
'category_id' => $this->input->post('category_id'),
'image' => $file_name
);
$insert = $this->game->save($data);
echo json_encode(array("status" => TRUE));
}

public function ajax_update() {
$this->_validate();
$data = array(
'title' => $this->input->post('title'),
'iframe' => $this->input->post('iframe'),
'status' => $this->input->post('status'),
'category_id' => $this->input->post('category_id')
);
$this->game->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}

HTML

<div class="container">
<h1 style="font-size:20pt">Games</h1>
<h3>Game Data</h3>
<br />
<button class="btn btn-success" onclick="add_game()"><i class="glyphicon glyphicon-plus"></i> Add Game</button>
<button class="btn btn-default" onclick="reload_table()"><i class="glyphicon glyphicon-refresh"></i> Reload</button>
<br />
<br />
<table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Title</th>
<th>Category</th>
<th>Status</th>
<th style="width:125px;">Action</th>
</tr>
</thead>
<tbody>
</tbody>

<tfoot>
<tr>
<th>Title</th>
<th>Category</th>
<th>Status</th>
<th>Action</th>
</tr>
</tfoot>
</table>
</div>

Javascript

<script type="text/javascript">

var save_method; //for save method string
var table;

$(document).ready(function () {

//datatables
table = $('#table').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.

// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('game/ajax_list') ?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [-1, -3], //last column
"orderable": false, //set not orderable
},
],
});

//set input/textarea/select event when change value, remove class error and remove text help block
$("input").change(function () {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function () {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function () {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});

});



function add_game()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Game'); // Set Title to Bootstrap modal title
}

function edit_game(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string

//Ajax Load data from ajax
$.ajax({
url: "<?php echo site_url('game/ajax_edit/') ?>/" + id,
type: "GET",
dataType: "JSON",
success: function (data)
{

$('[name="id"]').val(data.id);
$('[name="title"]').val(data.title);
$('[name="iframe"]').val(data.iframe);
$('[name="status"]').val(data.status);
$('[name="category_id"]').val(data.category_id);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Game'); // Set title to Bootstrap modal title

},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}

function reload_table()
{
table.ajax.reload(null, false); //reload datatable ajax
}

function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled', true); //set button disable
var url;

if (save_method == 'add') {
url = "<?php echo site_url('game/ajax_add') ?>";
} else {
url = "<?php echo site_url('game/ajax_update') ?>";
}

// ajax adding data to database
$.ajax({
url: url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function (data)
{

if (data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
} else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="' + data.inputerror[i] + '"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="' + data.inputerror[i] + '"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable


},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable

}
});
}

function delete_game(id)
{
if (confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url: "<?php echo site_url('game/ajax_delete') ?>/" + id,
type: "POST",
dataType: "JSON",
success: function (data)
{
//if success reload ajax table
$('#modal_form').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});

}
}

</script>

<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h3 class="modal-title">Game Form</h3>
</div>
<div class="modal-body form">

<?php
$attributes = array(
'id' => 'form',
'class' => 'form-horizontal'
);

echo form_open_multipart('#', $attributes);
?>
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Title</label>
<div class="col-md-9">
<input name="title" placeholder="Title" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Iframe</label>
<div class="col-md-9">
<textarea name="iframe" placeholder="Iframe" class="form-control" type="text"></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Category</label>
<div class="col-md-9">
<select name="category_id" class="form-control">
<option value="">--Select Category--</option>
<?php foreach ($categories as $category) { ?>
<option value="<?php echo $category['id'] ?>"><?php echo $category['name'] ?></option>
<?php } ?>
</select>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Image</label>
<div class="col-md-9">
<?php echo form_upload(['name' => 'image']); ?>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Status</label>
<div class="col-md-9">
<select name="status" class="form-control">
<option value="">--Select Status--</option>
<option value="0">Inactive</option>
<option value="1">Active</option>
</select>
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal -->

最佳答案

注意到代码中遗漏的几个必需条件

首先在您的 ajax_add 方法中

if ($this->upload->do_upload()) 这应该包含图像字段名称,例如

if ($this->upload->do_upload('image')){// as your file upload field name is "image"

}

然后,对于 ajax 上传的客户端代码,缺少一些参数

 contentType: false,
processData: false,

所以你的ajax方法应该(在save方法中)看起来像

$.ajax({
url: url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
contentType: false,
processData: false
.....

processData 这在通过 ajax 上传文件时很重要

关于php - 在 codeigniter 中使用 AJAX 上传文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34509934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com