对不起,我的英语,我希望你能理解我的问题...
在我的程序中,当您使用模式+表单向数据库(MySQL)提交新记录时,它会在数据表中绘制而不刷新或重新加载实际页面,它是动态附加的。
我需要做的是,在每条新记录中,使用新数据的 ID 绘制/附加数据和 2 个按钮(1 个用于删除该记录,1 个用于更新它)。
我读到我可以使用 insert_id() 来获取最后插入的 id,但我不知道如何使用它以及如何在我的 Ajax 调用中处理结果。
请问有什么提示吗?我对编程很陌生。
谢谢你的时间。
编辑
我需要我在模态/表单中引入的数据(因为我正在使用.serialize())和在数据库中生成的 ID ...我不知道如何使用模型/控制器返回的 ID 信息。
我的控制器中有这个:
public function nuevo_elemento_diccionario()
{
$this->load->helper('form');
$this->load->library('form_validation');
// Validation rules that I deleted for this post
if ($this->form_validation->run() === FALSE)
{
$this->load->view("header");
$this->load->view("section-aside");
$this->load->view("vista_nuevo_elemento_diccionario", $datos);
$this->load->view("footer");
}
else
{
$last_id = $this->mod_diccionarios->nuevo_elemento_diccionario();
echo json_encode(array('last_id' => $last_id));
redirect('/diccionarios/lista_diccionarios');
}
}
模型:
public function nuevo_elemento_diccionario()
{
$datos = array(
'ELDI_Key' => $this->input->post('eldi_key'),
'ELDI_Display' => $this->input->post('eldi_display'),
'ELDI_SuDiccionario' => $this->input->post('eldi_sudiccionario'),
);
$this->db->insert('elementos_diccionario', $datos);
/* $ultima_id = $this->db->insert_id();*/
$last_id = $this->db->insert_id();
return $last_id;
}
Javascript/Ajax(你看到 var key = $('input[name="eldi_key"]').val(); 并使用它,是我需要使用 ID 来使用新 ID 进行删除和更新点击的地方生成的按钮):
function nuevo_elemento()
{
var id =$('input[name="eldi_id"]').val();
var display = $('input[name="eldi_display"]').val();
var key = $('input[name="eldi_key"]').val();
key = key.split(" ").join("_").toLowerCase();
swal({
title: 'Añadir elemento',
text: "¿Quieres añadir este elemento?",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Sí',
cancelButtonText: 'No'
}).then((result) => {
if (result.value) {
$.ajax({
type: "POST",
url: $("#base_url").attr("valor") +
"diccionarios/nuevo_elemento_diccionario",
data: $("#formNuevoElementoDiccionario").serialize(),
success: function(data) {
console.log(data);
$('#Modal_Add').modal('hide');
$("#formNuevoElementoDiccionario").trigger("reset");
var html =
'<tr>'+
'<td>' + key + '</td>' +
'<td>'+ display +'</td>'+
'<td>'+
'<span class="btn btn-default editar_elemento"
id=' + key + ' value="' + key + '">' +
'<a href="'+$("#base_url").attr("valor") +
"diccionarios/elemento_diccionario/"+key+'" title="Editar">' +
'<i class="material-icons">edit</i>' +
'</a>' +
'</span>' +
'</td>' +
'<td>' +
'<span class="btn btn-default borrar_elemento"
id="'+ key +'" value="'+ key +'">'+
'<i class="material-
icons">delete_outline</i>'+
'</span>'+
'</td>'+
'</tr>'
$('#tabla-diccionarios').append(html);
swal("Añadido", "Elemento añadido correctamente",
"success");
$(".borrar_elemento").off();
evento_borrar_elemento();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error: " + textStatus);
}
});
}
})
}