ajax jquery不返回选择查询结果

时间:2013-02-24 06:39:47

标签: jquery codeigniter

所以,我的视图文件中有一个文本字段,它获取员工代码,jquery调用控制器中的一个函数,以便员工详细信息立即填写同一视图页面中的某些字段。但我是股票,没有任何事情真的发生,请参阅我的代码,并帮助我做到这一点。 谢谢!

jquery的:

$('#employee_code').change(function(){  
    var em_code = $('#employee_code').val();
    if (em_code != ""){
        var post_url = "<?php echo base_url();?>index.php/it_inventory/get_employee_details/" + em_code;
        $.ajax({
            type: "POST",
            url: post_url,
            success: function(name,position,department) 
            {
                $('#employee_name').val(name);
                $('#employee_position').val(position);
                $('#employee_department').val(department);
            }
        }); 
    }          
});

CI控制器:

function get_employee_details($em_code="") {
        header('Content-Type: application/x-json; charset=utf-8');
        echo(json_encode($this->it_inventory_model->get_employee_details($em_code)));
    }

CI模型

function get_employee_details($em_code){
        $q = "select name,position,department from employees where code=?";
        $query_em_detail=$this->db->query($q,$em_code);

        $outputs = array();

        if($query_em_detail->result()){
            foreach ($query_em_detail->result() as $output) {
                $outputs['name'] = $output->name;
                $outputs['position'] = $output->position;
                $outputs['department'] = $output->department_code;
            }
            return $outputs;
        } else {
            return FALSE;
        }
    }

2 个答案:

答案 0 :(得分:1)

您应该在ajax请求中添加dataType,例如:

$.ajax({
   type: "POST",
   url: post_url,
   dataType: "json",
   success: function(data) {
      console.log(data); //response from your controller
      console.log( data.name); //to get name
   },
   error: function() { alert("Something went wrong!"); }
});

和控制器:

function get_employee_details($em_code="") {
  header('Content-Type: application/json',true);
  echo(json_encode($this->it_inventory_model->get_employee_details($em_code)));
}

答案 1 :(得分:0)

我认为success: function(name,position,department)应为success: function(result)。然后,您需要使用result.nameresult.position

success: function(result) {
    $('#employee_name').val(result.name);
    $('#employee_position').val(result.position);
    $('#employee_department').val(result.department);
}