JQuery拼接多字段为地址列显示返回null问题求助
Fixing the Concatenated Address Column Issue
The problem here is that you're trying to reference a non-existent property name in your data object by concatenating field names into a string (like "vndr_address,state-vndr_pincode"). Since your JSON response doesn't have a property with that exact name, it returns null. Here's how to fix it:
Corrected jQuery Code
$(function() { $("#search").keyup(function() { var value = $(this).val(); $.ajax({ url : "<?php echo base_url();?>Vendorcontroller/search", type: "POST", data: { name: value }, success: function(response){ var data = $.parseJSON(response); var tbody = $('#myTable tbody').empty(); $.each(data, function(i, item) { // Rename inner variable to avoid shadowing var tr = $('<tr>'); // Add Vendor Name column $('<td>').html(item.vndr_name).appendTo(tr); // Build and add concatenated Address column var fullAddress = ''; if (item.vndr_address) fullAddress += item.vndr_address; if (item.state) { fullAddress += fullAddress ? ', ' : ''; // Add comma only if address exists fullAddress += item.state; } if (item.vndr_pincode) { fullAddress += fullAddress ? ' - ' : ''; // Add dash only if address/state exists fullAddress += item.vndr_pincode; } $('<td>').html(fullAddress).appendTo(tr); // Add remaining columns (mobile, telephone, mailid) ['vndr_mobile', 'vndr_telephone', 'vndr_mailid'].forEach(function(field) { $('<td>').html(item[field] || '').appendTo(tr); // Use empty string if value is null }); // Add Edit link $('<td>').html("<a href='<?php echo base_url();?>Vendorcontroller/edit/"+item.vndr_id+"'><i class='fa fa-edit fa-2x'></i></a>").appendTo(tr); // Add Delete link $('<td>').html("<a class='delete'href='#?id="+item.vndr_id+"'><i class='fa fa-remove fa-2x'></i></a>").appendTo(tr); tbody.append(tr); }); } }); }); });
Key Changes Explained
- Removed Invalid Property Reference: Instead of trying to use a concatenated string as a property name, we manually build the address by accessing each field individually (
item.vndr_address,item.state,item.vndr_pincode). - Handle Empty Values: Added checks to avoid extra commas/dashes if any of the address fields are null or empty.
- Variable Name Clarity: Renamed the inner
datavariable toitemto avoid shadowing the outerdatavariable (the parsed JSON response). - Cleaner Column Loop: Used a forEach loop for the remaining columns to keep the code organized.
This approach will correctly display the concatenated address in your table without returning null values.
内容的提问来源于stack exchange,提问作者itsme
相关产品推荐
相关产品推荐

