通过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 == 85condition, 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.vendorNamecorrectly. Choose the rendering option that fits your page's HTML structure.
内容的提问来源于stack exchange,提问作者dhananjana

