You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过onClick将PHP CodeIgniter数组传入JavaScript函数?

解决CodeIgniter中通过onClick传递数组到JavaScript的问题

问题根源

你当前的代码中,json_encode生成的JSON字符串直接嵌入到onClick的双引号属性里,会引发引号语法冲突(比如JSON里的双引号会打断onClick的属性值),同时JavaScript会把数组字面量识别为多个独立参数,而非单个数组对象。

修正方案

1. 调整Controller中的按钮输出

修改按钮的onClick参数传递逻辑,用单引号包裹JSON字符串并转义内部引号,避免语法错误:

function get_class_students_mass_pdf($class_id) {
    // 提前获取运行年份,避免重复查询
    $running_year = $this->db->get_where('settings', array('type' => 'running_year'))->row()->description;
    $students = $this->db->get_where('enroll', array(
        'class_id' => $class_id, 
        'year' => $running_year
    ))->result_array();
    
    $invoiceid = array();
    foreach ($students as $row) {
        $invoice_row = $this->db->get_where('invoice', array('student_id' => $row['student_id']))->row();
        // 避免无对应invoice时触发报错
        if (!empty($invoice_row)) {
            $invoiceid[] = $invoice_row->invoice_id;
        }
    }

    $invoice_json = json_encode($invoiceid);
    // 转义JSON中的引号,确保嵌入到HTML属性中不冲突
    $safe_invoice_json = addslashes($invoice_json);
    
    echo '<br><br><button style="margin-left: 36px;" type="button" class="btn btn-default" onClick="invoice_view_modal(\'' . $safe_invoice_json . '\')"> ' . get_phrase('generate_pdf') . ' </button>';
}

2. 修改View中的JavaScript函数

在JS函数中解析JSON字符串为数组,再转换为适合URL传递的格式:

function invoice_view_modal(invoiceJson) {
    // 将JSON字符串解析为JavaScript数组
    const invoiceIds = JSON.parse(invoiceJson);
    
    // 方案1:转为逗号分隔的字符串传递给后端
    const invoiceStr = invoiceIds.join(',');
    showAjaxModal('<?php echo site_url('modal/popup/modal_view_mass_invoice/');?>' + invoiceStr);

    // 方案2:若后端支持接收JSON,可URL编码后传递
    // const encodedInvoice = encodeURIComponent(invoiceJson);
    // showAjaxModal('<?php echo site_url('modal/popup/modal_view_mass_invoice/');?>' + encodedInvoice);
}

3. 后端接收逻辑调整(可选)

如果用逗号分隔字符串传递,后端modal_view_mass_invoice方法需将字符串转回数组:

function modal_view_mass_invoice($invoice_str) {
    $invoice_ids = explode(',', $invoice_str);
    // 后续业务逻辑处理
}

如果用URL编码的JSON传递,后端则解码并解析:

function modal_view_mass_invoice($encoded_json) {
    $invoice_json = urldecode($encoded_json);
    $invoice_ids = json_decode($invoice_json, true);
    // 后续业务逻辑处理
}

内容的提问来源于stack exchange,提问作者Shair Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 19:51:53