更新:这现在可以 100% 工作。
这些代码段允许用户单击视图上的“删除”按钮,这会向我的控制器发送 AJAX 请求以与数据库进行交互(删除记录)。然后反馈回调函数中发生的结果,以更新记录被删除的当前视图(没有页面加载)并隐藏元素。
看法:
<?php
// Output the records
if($result)
{
foreach ($result as $rows => $row)
{
echo "<tr id=\"row" . $row['id'] . "\">";
echo "<td>" . $row['id'] . " - " . $row['name'] . "</td>";
echo "<td>" . $row['logo_path'] . "</td>";
echo "<td>" . $row['date_created'] . "</td>";
echo "<td>" . "<a href=\"#\" id=\"" . $row['id'] . "\" class=\"delete\">Delete</a><br>" . "</td>";
echo "</tr>";
}
} else {
echo "There are no platforms to show";
}
?>
<script type="text/javascript">
$("a.delete").click(function(e)
{
e.preventDefault();
var platform_id = $(this).attr('data-id');
var row = $(this).attr('id');
$.ajax({
type: "POST",
url: "platform/delete",
dataType: "json",
data: 'platform_id='+platform_id,
success: function(result){
if (result.success == 1)
{
$("#row" + row).fadeOut();
//document.getElementById(row).style.display = 'none'
}
},
error: function(result){
alert(result.message);
}
});
});
</script>
控制器:
function delete()
{
$result=array();
$this->load->model('platform_model');
$platform_id = $this->input->post('platform_id');
if($this->platform_model->delete($platform_id))
{
$result['success']= 1;
$result['platform_id']= $platform_id;
$result['message']= "Success";
} else {
$result['success']= 0;
$result['message']= "Error";
}
die(json_encode($result));
}
模型:
function delete($platform_id)
{
$this->db->where('id =', $platform_id);
if ($this->db->delete('platforms'))
{
return TRUE;
}
else
{
return FALSE;
}
}