【问题标题】:AJAX data post in Codeigniter not workingCodeigniter 中的 AJAX 数据发布不起作用
【发布时间】:2015-08-20 11:28:34
【问题描述】:

我在 ajax 发布时遇到问题。在下拉列表中选择父类别时,我尝试获取类别。但数据已发布。

我的业务主管

 public function getcat($id)
{
    echo "sdfad";
    $cr=new Categoryrepo();
    header('Content-Type: application/x-json; charset=utf-8');
    echo(json_encode($cr->getcatbyparentid($id)));
}

我的类别模型

 public function getcatbyparentid($id)
{
    $this->db->select('id,name');
    $this->db->from('category');
    $this->db->where('parent',$id);
   return $query=$this->db->get();
}

我的 ajax 代码

 $(document).ready(function(){
   $("#parent").change(function(){
        var id=$('#parent').val();
        alert(id);
        $.ajax({
            type:"POST",
            url:"<?php echo base_url()?>business/getcat/"+id,
            success: function(data)
            {
                alert(data);
            }
        });
    });
});

请帮我解决一下

【问题讨论】:

  • 好吧,在您的模型中,您没有从数据库返回任何结果。因此,您应该根据您的要求使用result() 或 Codeigniter documentation 的任何其他功能。而且,我真的没有得到你真正需要的东西。您是否在如何填充子下拉列表时遇到问题?还是因为返回的数据不正确??
  • 结果如何,打印出来。你的问题不完整。同时向我们展示console 错误。

标签: php jquery ajax codeigniter


【解决方案1】:

现在它工作...... Json 返回正确的数据,例如 [{"id":"8","name":"mobile"},{"id":"10","name":"mno`"}]。

现在的问题是如何在下拉列表中绑定这些数据..

【讨论】:

    【解决方案2】:

    试试这个:

    型号:

    public function getcatbyparentid($id){
        $this->db->select('id,name');
        $this->db->from('category');
        $this->db->where('parent',$id);
        // just return query! In controller we will handle it.
        return $query;
    }
    

    控制器:

    $this->load->model("Categoryrepo");
    $html = $this->Categoryrepo->getcatbyparentid($id);
    $content  = "<select name='yourName'>";
    foreach($html->result() as $row){
        $content .= '<option value="'. $row->column_name1 .'">' . $row->column_name2 . "</option>";
    }
    $content .= "</select>";
    $result = array('status' => 'ok', 'content' => $content);
    echo json_encode($result);
    

    【讨论】:

      【解决方案3】:

      修改你的模型函数如下:

      public function getcatbyparentid($id)
      {
          $this->db->select('id,name');
          $this->db->where('parent',$id);
          $query=$this->db->get('category');
          if($query->num_rows() == 0)
          {
              return FALSE;
          }
          else
          {
              return $query->result() // or return $query->row() <if you want only one value to be return>
          }
      }
      

      【讨论】:

      • 为什么我的回答被视为否定?
      猜你喜欢
      • 2019-06-26
      • 1970-01-01
      • 2016-08-11
      • 1970-01-01
      • 2021-04-30
      • 2018-12-11
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      相关资源
      最近更新 更多