【问题标题】:Getting data by ajax in Codeigniter在 Codeigniter 中通过 ajax 获取数据
【发布时间】:2018-07-14 12:13:56
【问题描述】:

我在 CI 中通过 ajax 向数据库添加记录,所以我试图返回新记录的 id 但它不起作用,记录已添加但没有返回 id。(在 ajax 代码中我试图提醒新的记录 ID,但它正在警告未定义)

下面是ajax代码:

$.ajax({
type:'post',
url: baseURL+"admin/Products/add_product",
data:postData,
  success:function(data){

alert(data[0].id);
  $('#register_form')[0].reset();


}  });

这是控制器,

注意是从create_product方法返回id,放到get_by_id方法中,然后返回结果

  if($id=$this->Products_model->create_product($data)){
$result = $this->Products_model->get_product_by_id($id);
 return $result;

       }    

这是我的模型方法

public function create_product($data){


   $query = $this->db->insert('products',$data);

  if($query){


$id = $this->db->insert_id();

     return $id;

 }else{
    return false;
 } 

    }

 //////////get_by_id_method
    public function get_product_by_id($id){
    $this->db->where($id,'id');
    $query = $this->db->get('products');

    if($query){



        return $query->result();
    }

    }

【问题讨论】:

    标签: ajax codeigniter codeigniter-3 codeigniter-query-builder


    【解决方案1】:

    希望对您有所帮助:

    你的ajax应该是这样的:

    $.ajax({
      type:'post',
      url: baseURL + "admin/Products/add_product",
      data:postData,
      success:function(data)
      {
        var response = JSON.parse(data);
        alert(response.id);
        $('#register_form')[0].reset();
      }  
    });
    

    你的控制器应该是这样的:

    $id = $this->Products_model->create_product($data);
    if($id)
    {
      $result = $this->Products_model->get_product_by_id($id);
      echo json_encode($result);
      exit;
    }
    

    你的模型方法get_product_by_id应该是这样的:

    public function get_product_by_id($id)
    {
      $this->db->where($id,'id');
      $query = $this->db->get('products');
      if($query->num_rows() > 0)
      {
        return $query->row();
      }
    }
    

    【讨论】:

    【解决方案2】:

    您可能需要在控制器中使用正确的 Content-type 回显 JSON:

    $result = [];
    $id = $this->Products_model->create_product($data);
    
    if ($id) {
       $result = $this->Products_model->get_product_by_id($id);
    }
    
    header("Content-type: application/json");
    echo json_encode($result);
    

    这样响应可以是空对象或者查询结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 2015-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多