在ajax成功中打印返回值数组

时间:2019-05-17 07:48:14

标签: ajax codeigniter

我想在ajax成功中打印值数组

我的控制器代码是

function get_all_packages() {        
    $data['free_flow'] = $this->Api_model->get_free_flow_packages();
    $data['draft'] = $this->Api_model->get_draft_packages();
    print_r($data);
}

我的模型代码是

function get_free_flow_packages(){
    $this->db->select('*');
    $this->db->from('item');        
    $this->db->where('item.category_id', 1);
    $query = $this->db->get();
    return Json_encode($query->result_array());
}

我的Ajax代码是

      $(document).ready(function(){
                   alert('hello');
                   $.ajax({
                        type: "POST",
                        url: 
      "http://localhost/bartender_api/Api/get_all_packages/",                            
                        success: function (result) {
                            console.log(result.free_flow); 
                            console.log(result.draft);

                        }
                    });
               });

在这里,我将控制台两个数组值,但显示为空,如何打印两个数组值。

3 个答案:

答案 0 :(得分:0)

使用

代替在控制器函数中使用print_r
echo json_encode($data);

,然后在您的ajax中添加属性dataType:"JSON" 然后,您可以以free_flow的身份访问result.free_flow

答案 1 :(得分:0)

尝试一些更改

控制器

echo $data;

型号

json_encode而不是Json_encode()

 return json_encode($query->result_array());

Ajax请求(添加)

dataType: 'json'

答案 2 :(得分:0)

添加ajax选项:

dataType: 'json'

您还可以使用codeigniter本机输出类显示真实的json数据:

$this->output->set_content_type("application/json")->set_output($data);
相关问题