jquery - 我正在尝试在 Codeignitor 中调用 Ajax,但它不起作用
问题描述
我正在尝试通过 ajax 检查数据库中是否存在标题,但认为 ajax 调用不起作用。请通过一些建议帮助我。
在视图中
<input type="text" class="form-control" id="cs_title" name="cs_name">
<span id="title_result"></span>
<script>
$(document).ready(function()
{
$("#cs_title").change(function(){
var title = $("#cs_title").val();
if (title != '') {
$.ajax({
url: "<?php echo base_url(); ?>back_end/check_title",
method:"POST",
data:{title:title},
success:function(data) {
$('#title_result').html(data);
}
});
}
});
});
</script>
在控制器中
public function check_title()
{
if ($this->cs_model->check_title($_POST['title'])) {
echo '<label class="text-danger"><span class="glyphicon glyphicon-remove"></span> Title Already Exist</label>';
}
else {
echo '<label class="text-success"><span class="glyphicon glyphicon-ok"></span> Title Available</label>';
}
}
在模型中
public function check_title($title)
{
$this->db->where('cs_title',$title);
$title_count = $this->db->get('case_study')->num_rows();
if ($title_count > 0) {
return true;
}
else {
return false;
}
}
解决方案
在你的模型中试试这个:
public function check_title($title)
{
$title_count = $this->db->where('cs_title', $title)
->count_all_results('case_study');
return $title_count;
}
在您的控制器中:
public function check_title($title)
{
$data['check'] = $this->cs_model->check_title($title);
echo json_encode($data);
}
在您的视图中:
<input type="text" class="form-control" id="cs_title" name="cs_name">
<span id="title_result"></span>
<script>
$(document).ready(function()
{
$("#cs_title").keyup(function()
{
var title = $(this).val();
$.getJSON("<?php echo base_url("back_end/check_title/") ?>" + title, function(data)
{
$("#title_result").empty();
if( data.check > 0 ) {
$("#title_result").append('<label class="text-danger"><span class="glyphicon glyphicon-remove"></span> Title Already Exist</label>');
} else {
$("#title_result").append('<label class="text-danger"><span class="glyphicon glyphicon-remove"></span> Title Already Exist</label>');
}
});
});
}
</script>
推荐阅读
- java - JOptionPane.showInputDialog() 使程序崩溃而没有错误。(窗口停止响应)
- multidimensional-array - xarray 按多个维度切片数据
- mysql - 依靠查询结果运行另一个nodejs mysql
- python - 用值填充熊猫系列的一部分
- python - json/python dict中出现奇怪的双反斜杠
- google-sheets - 谷歌表格使数据验证选择今天的年/月/周打开
- r - How to ignore error message in R and keep loop function going
- javascript - Problem with uploading a image via Ajax Call in php?
- html - Last-Child in nested div
- angular - 使用命名路由器出口实现多个子路由