使用jQuery AJAX请求CodeIgniter显示从Controller到View的数据库

使用jQuery AJAX请求CodeIgniter显示从Controller到View的数据库

问题描述:

I am having a problem in fetching data from database using jQuery AJAX as json datatype I have read and tried JSON.parse in jQuery but it did not work. All I am returning in console.log(data) is object and the data from database in object but I don't know how to show it on view. Any suggestions please.

Here is my Controller.

  function fetch(){
                $data_fetch     = array(
                    'id'        => $this->input->post('txt_id')
                    );
                $data['records'] = $this->form_model->fetch_model($data_fetch);
        $results    = json_encode($data);

            $this->output->set_content_type('application/json');
            $this->output->set_output($results);
        }

Here is my jQuery AJAX

$.ajax({
            type    : 'POST',
            url     :  base_url + 'index.php/form_controller/fetch',
            data    : {txt_id : id },
            dataType : 'JSON',
            success : function(data){
                // var re = JSON.parse(data);
                // var re = $.parseJSON(data);
                // var data = JSON.parse(data);
                alert(data.name);
                console.log(data);

            },
            error   : function(data){
                console.log('erronr in fetch');
            }
        });

The data.name is showing undefined in alert. Any help will be appreciated.

我在使用jQuery AJAX作为json数据类型从数据库中获取数据时出现问题我已阅读并尝试过JSON.parse 在jQuery但它没有用。 我在 console.log(data) code>中返回的所有内容都是 object code>和来自对象中数据库的数据,但我不知道如何在视图中显示它。 请给我任何建议。 p>

这是我的控制器。 p>

  function fetch(){
 $ data_fetch = array(
'id  '=> $ this-> input-> post('txt_id')
); 
 $ data ['records'] = $ this-> form_model-> fetch_model($ data_fetch); 
  $ results = json_encode($ data); 
 
 $ this-> output-> set_content_type('application / json'); 
 $ this-> output-> set_output($ results); 
 这是我的jQuery AJAX  p> 
 
 
  $。ajax({
 type:'POST',  
 url:base_url +'index.php / form_controller / fetch',
 data:{txt_id:id},
 dataType:'JSON',
 success:function(data){
 // var re =  JSON.parse(data); 
 // var re = $ .parseJSON(data); 
 // var data = JSON.parse(data); 
 alert(data.name); 
 console.log( 数据 ); 
 
},
错误:函数(数据){
 console.log('获取中的错误'); 
} 
}); 
  code>  pre> 
  
 

data.name code>在alert中显示 undefined code>。 任何帮助将不胜感激。 p> div>

You don't need to use JSON.parse the variable data is already a JSON, so just use it as a you would with any other JSON.