如何将codeigniter DB数组传递给javascript函数

时间:2013-11-01 02:22:45

标签: javascript arrays codeigniter

我在codeigniter中有这个数据库数组,我想把它传递给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;
}

获取$ 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);

}

$ 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. ..
}

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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
}