0

因此,我的视图文件中有一个文本字段,用于获取员工代码,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;
        }
    }
4

2 回答 2

1

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

$.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)));
}
于 2013-02-24T06:54:06.157 回答
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);
}
于 2013-02-24T06:53:59.607 回答