我正在尝试通过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;
}
}
答案 0 :(得分:0)
在您的模型中尝试一下:
public function check_title($title)
{
$title_count = $this->db->where('cs_title', $title)
->count_all_results('case_study');
return $title_count;
}
在您的 Controller 中:
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>