如何用表格展示Ajax获取的数据(替代只读Input标签)
Solution: Switch to Table Layout for Displaying Ajax Data
Let's replace those read-only inputs with a clean, responsive table that's better suited for showing static details. Here's how to update your code step by step:
1. Updated view.blade Modal Body
Swap out the entire <form> section in your modal body with this table structure (using Bootstrap table classes for built-in styling):
<div class="modal-body" style="font-size: 10px;"> <table class="table table-bordered table-sm"> <tbody> <tr> <td width="20%"><strong>Name</strong></td> <td id="name2"></td> </tr> <tr> <td><strong>Email/Username</strong></td> <td id="email2"></td> </tr> <tr> <td><strong>Address</strong></td> <td id="address2"></td> </tr> <tr> <td><strong>Phone Number</strong></td> <td id="phone_number2"></td> </tr> <tr> <td><strong>Household Type</strong></td> <td id="type2"></td> </tr> <tr> <td><strong>Active Status</strong></td> <td id="active_status2"></td> </tr> <tr> <td><strong>Password</strong></td> <td id="password2"></td> </tr> <tr> <td><strong>Transactions</strong></td> <td id="transactions2"></td> <!-- Added a proper ID for this field --> </tr> </tbody> </table> </div>
2. Updated Script Code
Since we're now working with table cells instead of input fields, we'll use .text() instead of .val() to populate data. Also fixed a small typo in the modal selector (your modal's ID is viewInfo, not viewInfo2):
$('.view_data').click(function(event){ event.preventDefault(); var household_id = $(this).attr("id"); $.ajax({ url:"{{ route('householdInfo') }}", method:"get", data:{household_id:household_id}, dataType:"json", success:function(data){ // Fill table cells with retrieved data $('#name2').text(data.firstname); $('#address2').text(data.address); $('#phone_number2').text(data.phone_number); $('#type2').text(data.type); $('#email2').text(data.email); $('#active_status2').text(data.active_status); $('#password2').text(data.password); // Add fallback text if transactions data is missing $('#transactions2').text(data.transactions || 'No transactions recorded'); // Trigger the modal to show $('#viewInfo').modal('show'); console.log(data); } }); });
Quick Notes:
- Table Styling: Used Bootstrap's
table-borderedandtable-smclasses to keep the table compact and easy to read. Adjust the first column's width (set to 20% here) if needed. - Transactions Field: Added a dedicated ID and fallback text to handle cases where no transaction data is returned.
- Modal Fix: Corrected the modal selector to target the correct ID in your blade file.
This table layout will make your read-only data look more organized and professional compared to the form input approach.
内容的提问来源于stack exchange,提问作者MaxiMango




