2017-01-27 37 views
0

私は比較的新しいcodeigniterです。 AJAXを使用してデータベースで検索操作を実行しようとしている間、コードは正常に返され、データは取得されますが、このデータはJSONエンコードされており、ビューのjavascript部分にあります。コードシニターのjson_decode関数CodeigniterでAJAXで返されたJSONエンコードデータを使用

public function lookup(){ 
    $keyword = $this->input->post('term'); 
    $data['response'] = 'false'; //Set default response 
    $query = $this->MAutocomplete->lookup($keyword); //Search DB 
    if(! empty($query)) 
    { 
     $data['response'] = 'true'; //Set response 
     $data['message'] = array(); //Create array 
     foreach($query as $row) 
     { 
      $data['message'][] = array( 
            'id'=>$row->id, 
            'value' => $row->firstname, 

           ); //Add a row to array 
     } 
    }   
     echo json_encode($data); //echo json string 
} 

データは、data.messageとしてjavascriptでアクセスされます。 私は私はあなたがこの.Like JSON.parse()を使用してのAjaxの成功の機能でJSONレスポンスを解析する必要があると思う私のプログラム

<?php 
class MAutocomplete extends CI_Model{ 
function lookup($keyword){ 
    $this->load->database(); 
    $this->db->select('*'); 
    $this->db->from('Students'); 
    $this->db->like('firstName',$keyword,'after'); 
    $query = $this->db->get();  
    // echo '<pre>'; print_r($query->result()); exit; 
    return $query->result(); 
} 
} 
+0

あなたのモデルの機能を投稿することはできますか?結果形式データベースはどの形式で取得できますか? –

+0

@HikmatSijapati私は要求されたようにモデルコードを追加しました –

+0

答えを参照してくださいあなたはそれを解決しました。 –

答えて

0

のPHPの一部で、このデータを使用することができます。..

$.ajax({ 
url:'',//your url 
dataType:'JSON', 
data:'',//your data 
success:function(response){ 
data = JSON.parse(response); 
alert(data.message.value);//alerts value 
} 
}); 
とにかくあり教えてください配列

if(count($query) >0) 
    { 
     $data['response'] = 'true'; //Set response 
     $data['message'] = array(); //Create array 
     foreach($query as $row) 
     { 
      $data['message'][] = array( 
            'id'=>$row->id, 
            'value' => $row->firstname, 

           ); //Add a row to array 
     } 
    }  
をチェックempty.Toのではなく countコントローラの使用では

0
あなたが応答に使用する必要があり

return $this->output 
     ->set_content_type('application/json') 
     ->set_output(json_encode($data)); 
関連する問題