2013-11-01 41 views
0

我在codeigniter中有這個數據庫數組,我想將它傳遞給javascript函數。可能嗎?如何將codeigniter DB數組傳遞給javascript函數

MODEL:

public function show_employment_skills($P1) 
{ 
    $this->db->select('*'); 
    $this->db->from('employee_skills'); 
    $this->db->where('emp_id', $P1); 
    $this->db->order_by('ID', 'desc'); 

    $query = $this->db->get(); 

    if($query->num_rows() > 0) 
    { 
     foreach ($query->result() as $row) 
     { 
      $data[] = array(
        'id' => $row->ID, 
        'emp_id' => $row->emp_id, 
        'skills' => $row->skills 


       ); 
     } 
    } 
    else 
    { 
     $data = ""; 
    } 
    return $data; 
} 

,並獲得$數據(?這是一個DB陣列,右)後

這裏是我的控制器

public function swoosh_employment_skills() 
{ 
    $P1 = $this->session->userdata('id'); 

    $set['record_skills'] = $this->emp->show_employment_skills($P1); 
    $this->load->view('swoosh_template/employee/employmentskills',$set); 

} 

的$組[ 'record_skills' ]是陣列來自數據庫..

現在這裏是我的看法:

<?php if ($record_skills != "") } ?> 
<table class="table table-bordered"> 
<tr> 
    <th>Skills</th> 
<th style='width:50px;'>Alert it!</th> 
</tr> 
<?php foreach ($record_skills as $row): ?> 
<tr> 
    <td class="skills"><?php echo $row['skills'];?></td> 
    <td><img src=alert_it.png onclick="show(db array that i should put. but how?);"</td> 
</tr> 
</table> 

這裏是JavaScript

function show(array){ 
//in here i should alert all the values of arrays. .. 
} 

回答

1

你可以使用json_encode()爲,如:

<img src=alert_it.png onclick="show(<?php echo json_encode($your_array); ?>);" /> 

和JS

function show(arr){ 
console.log(arr); //check the array format and loop 
} 
+0

確定。我會試試看。 :) – Vincent

+0

這裏的結果「function Array(){[native code]}」 – Vincent

2

試試這個:

<img src=alert_it.png onclick="show('<?php echo json_encode($your_array); ?>');" /> 

然後將字符串傳遞給JS中的功能,然後在JS可以解碼該字符串作爲JSON:

function show(arr){ 
    var _json = $.parseJSON(arr); 
    console.log(_json); //check the array format and loop 
}