首页 > 解决方案 > 我正在尝试在 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;
    }
  }

标签: jquerymysqlajaxcodeigniter-3

解决方案


在你的模型中试试这个:

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>

推荐阅读