请帮助我了解如何使用 codeigniter 和 jquery 从数据库中获取最后插入的 ID。我想要的是插入后获取最后插入的id。我正在使用 jquery 来插入数据。我不知道该怎么做。非常感谢。
脚本
$('#add-tag').click(function () {
var lang = $('#lang').val();
var tag = $('#tag').val();
var data = {
tag: tag,
lang: lang
}
if (tag === '') {
$('.error').html('<h4><i class="glyphicon glyphicon-info-sign">' +
'</i> Field cannot be empty!</h4>').addClass('bounceIn').show();
$('.error').delay(3000).fadeOut();
} else {
$.ajax({
url: "<?= site_url('blog/add_tag'); ?>",
type: 'POST',
data: data,
success: function (result) {
//display message if successful
$('.message').html('<h4><i class="glyphicon glyphicon-ok">' +
'</i> Tag has been added</h4>').addClass('bounceIn').show();
$('.message').delay(3000).fadeOut();
$('#tag').val('');
$('#tags').append('<a class="tags animated fadeInDown">' +
'<span class="remove-tag" id="remove-tag' + lid + '">' +
'</span></span> ' + tag + '</a>');
window.setTimeout(function () {
location.reload();
}, 2000);
}
});
}
});
查看
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div id="add-tag-form" class="display-none relative">
<div class="well well-sm">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<h5>Add Tag</h5>
<input type="text" id="tagLastID" class="form-control" placeholder="Tag Last ID" readonly>
<input type="hidden" id="lang" class="form-control" placeholder="Lang" required value="<?= $lang; ?>">
<input type="text" id="tag" class="form-control" placeholder="Tag" required>
<br />
<button id="add-tag" class="btn col-md-12 col-sm-12 col-xs-12">Add Tag</button>
<div class="text-center"><a id="close-tag">cancel</a></div>
</div>
</div>
</div>
</div>
<button id="add-tag-btn" class="btn col-md-12 col-sm-12 col-xs-12">Add Tag</button>
</div>
</div>
Controller
public function add_tag() {
$this->Mblog->addTag();
}
模型
public function addTag() {
$lang = $this->input->post('lang');
$tag = $this->input->post('tag');
$data = array(
'tags' => $tag,
'lang' => $lang
);
$this->blog->insert('tags', $data);
return $this->blog->insert_id();
}
最佳答案
将返回添加到您的 Controller 函数或回显如下结果:
public function add_tag() {
return $this->Mblog->addTag();
}
或
public function add_tag() {
echo json_encode(['data' => $this->Mblog->addTag()]);
exit;
}
然后尝试修改dump,查看ajax成功响应:
$.ajax({
url: "<?= site_url('blog/add_tag'); ?>",
type: 'POST',
data: data,
dataType: 'json', // this will convert your results to json by default
success: function (result) {
// You should get the json result
console.log(result.data);
// Your regular logic to handle result
},
fail: function(res) {
console.log(res); // will log fail results
}
});
试试这些,让我们知道这是否适合您。
关于php - 使用codeigniter和jquery插入后如何获取最后插入的ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39748379/