php 如何在 CodeIgniter 中使用 AJAX 从数据库中获取数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23911438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:02:08  来源:igfitidea点击:

How to get data from database using AJAX in CodeIgniter?

phpjqueryajaxjsoncodeigniter

提问by NiceTry

I wonder how to get data from database using AJAX in CodeIgniter. Could you please check the code below to find out the reason of problem? Nothing happens when I click on the link from my view.

我想知道如何在 CodeIgniter 中使用 AJAX 从数据库中获取数据。您能否检查下面的代码以找出问题的原因?当我从我的视图中单击链接时,没有任何反应。

Here is my view:

这是我的观点:

<a href="#" class="faq_title"><?php echo $faq_title; ?></a>

Here is my controller:

这是我的控制器:

public function get_faq_data() {
    $this->load->model("model_faq");
    $title = $_POST['title'];
    $data["results"] = $this->model_faq->did_get_faq_data($title);
    echo json_encode($data["results"]);
}

Here is my model:

这是我的模型:

public function did_get_faq_data($title) {
    $this->db->select('*');
    $this->db->from('faq');   
    $this->db->where('faq_title', $title); 

    $query = $this->db->get('faq');

    if ($query->num_rows() > 0) {
        return $query->result();
    } else {
        return false;
    }
}    

Here is my JavaScript file:

这是我的 JavaScript 文件:

$(".faq_title").click(function() {
    var title = $(this).text();

    $.ajax({
        url: 'faq/get_faq_data',
        data: ({ title: title }),
        dataType: 'json', 
        type: 'post',
        success: function(data) {
            response = jQuery.parseJSON(data);
            console.log(response);
        }             
    });
});

回答by Jai

Try this:

尝试这个:

$(function(){ // start of doc ready.
   $(".faq_title").click(function(e){
      e.preventDefault();  // stops the jump when an anchor clicked.
      var title = $(this).text(); // anchors do have text not values.

      $.ajax({
        url: 'faq/get_faq_data',
        data: {'title': title}, // change this to send js object
        type: "post",
        success: function(data){
           //document.write(data); just do not use document.write
           console.log(data);
        }
      });
   });
}); // end of doc ready


The issue as i see is this var title = $(this).val();as your selector $(".faq_title")is an anchor and anchors have text not values. So i suggested you to use .text()instead of .val().

我看到的问题是,var title = $(this).val();因为您的选择器$(".faq_title")是一个锚点,而锚点具有文本而不是值。所以我建议你使用.text()而不是.val().