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

如何获取并显示Ajax请求成功返回的响应数据

问题原因

你当前拿到的Ajax响应是分页结构数据,目标发票的明细字段全部嵌套在响应根对象的data数组中,你之前的代码直接从响应根对象取字段,层级错误所以取不到值。

修改后的代码

$('#invoice').change(function() {
    console.log('invoice selected!')
    const optionSelected = $(this).find("option:selected");
    const invoiceSelected = optionSelected.val();
    console.log(invoiceSelected);

    $.ajax({
        type: "get",
        cache: false,
        url: "{{ route('credit-notes.invoices') }}",
        data: { invoice: invoiceSelected },
        success: function(res) {
            console.log('success');
            console.log(res);

            // 场景1:接口传入invoice参数后,返回的data数组仅包含选中的对应数据,直接取第一条即可
            const targetInvoice = res.data[0];
            // 场景2:接口返回全量发票列表,用选中ID匹配对应条目
            // const targetInvoice = res.data.find(item => item.id == invoiceSelected);
            
            if (!targetInvoice) return; // 未匹配到数据时终止后续渲染逻辑

            const invoice_id = invoiceSelected;
            const invoice_name = targetInvoice.name;
            const invoice_date = targetInvoice.created_at;
            const invoice_description = targetInvoice.description;
            const invoice_amount = targetInvoice.amount;

            const row = `<tr id="row-${invoice_id}" class="invoice-row">
                <td><input type="checkbox"/>&nbsp;</td>
                <td>${invoice_name}</td>
                <td>${invoice_date}</td>
                <td>${invoice_description}</td>
                <td>${invoice_amount}</td>
            </tr>`;
            $('#invoice-tbody').append(row);
        }
    });
}).change();

额外优化建议

  • 每次追加新行前可先清空旧的表格内容,避免重复渲染,在渲染行之前添加$('#invoice-tbody').empty()即可
  • 日期如果需要转为国内常用格式,可以用new Date(invoice_date).toLocaleString()处理
  • 所有变量用const/let声明,避免产生隐式全局变量污染

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:06:05