Codeigniter使用json将变量传递给php文件

时间:2014-06-01 04:20:15

标签: php jquery ajax json codeigniter

我想从数据库中获取数据但我无法使用json将变量从视图传递到控制器。你能帮我找错吗?

以下是我的观点:

<?php
  echo $message;
  foreach($results as $row)
  {
      $faq_id = $row->faq_id;
      $faq_title = $row->faq_title;
?>

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

<?php 
   }
 ?>

这是我的JS文件:

$(".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); 
                                 }
           });

});

这是我的控制器:

 public function get_faq_data() {
           header('Content-Type: application/json',true);
           $this->load->model("model_faq");
           $title = $this->input->post('title');
           $data["results"] = $this->model_faq->did_get_faq_data($title);
           echo json_encode($data["results"]);

        }

这是我的模特:

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;
    }
   }    

1 个答案:

答案 0 :(得分:1)

var title = $(this).text();

$.post( // you can simply send json from post method of jquery
    "<?php echo site_url('faq/get_faq_data') ?>", // try to use full url
    {
        title : title
    },
    function( data ) {
        console.log( data );
    },
    "json"
);