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

通过AJAX获取JSON元素:CodeIgniter数据渲染问题求助

Hey there, let's fix this issue step by step! The core problem here is that your controller is outputting multiple separate JSON objects instead of a single valid JSON array. When you run echo json_encode($response); inside the loop, you're sending back something like {"vendorName":"Cinnamon Grand"}{"vendorName":"Saloon Bhagya"} — this isn't valid JSON syntax, so jQuery can't parse it into a proper JavaScript object/array when you set dataType:'json', hence the undefined error.

Fix the Controller Code

Instead of echoing each JSON object one by one, collect all matching vendors into an array first, then encode and echo the whole array once:

function vendorAccess(){
    $result = $this->Admin_model->allvendor();
    // Initialize an empty array to store all qualifying vendors
    $matchingVendors = [];
    
    foreach($result as $row){
        $data = $row["joinedDate"];
        $now = time();
        $your_date = strtotime($data);
        $datediff = $now - $your_date;
        $cont = round($datediff / (60 * 60 * 24));
        
        if($cont == 85){
            // Add the vendor to our collection array
            $matchingVendors[] = [
                'vendorName' => $row['vendorName']
            ];
        }
    }
    
    // Output the entire array as a single valid JSON string
    echo json_encode($matchingVendors);
}

Fix the AJAX Code

Now that we're getting a valid JSON array (it'll look like [{"vendorName":"Cinnamon Grand"},{"vendorName":"Saloon Bhagya"}]), we can loop through it and render each vendorName into your page divs. Here are two common implementation options:

$(document).ready(function(){
    $.ajax({
        url: '<?php echo base_url();?>/Admin/vendorAccess',
        type: 'get',
        dataType:'json',
        success: function(res){
            // Option 1: Populate pre-existing divs (e.g., #vendor-1, #vendor-2)
            res.forEach((vendor, index) => {
                $(`#vendor-${index}`).text(vendor.vendorName);
            });

            // Option 2: Dynamically create and append divs to a container
            // const vendorContainer = $('#vendor-container');
            // res.forEach(vendor => {
            //     vendorContainer.append(`<div class="vendor-item">${vendor.vendorName}</div>`);
            // });
        },
        error: function(xhr, status, error){
            // Optional: Add error handling for debugging
            console.error('AJAX Request Failed:', error);
        }
    });
});

What Changed?

  • The controller now builds a single array of all vendors that meet your $cont == 85 condition, then sends it as one valid JSON structure.
  • The AJAX call receives a proper array, so you can loop through each item and access vendor.vendorName correctly. Choose the rendering option that fits your page's HTML structure.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:14:43