要通过AJAX从Laravel Controller传递一个数组并在前端创建表格,你需要完成以下几个步骤:
// app/Http/Controllers/YourController.php
public function getData()
{
$data = [
['id' => 1, 'name' => 'Alice', 'age' => 25],
['id' => 2, 'name' => 'Bob', 'age' => 30],
// 更多数据...
];
return response()->json($data);
}
routes/web.php
中定义路由。Route::get('/get-data', [YourController::class, 'getData']);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX Table Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<table id="dataTable" border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<!-- 数据将通过AJAX加载到这里 -->
</tbody>
</table>
<script>
$(document).ready(function() {
$.ajax({
url: '/get-data', // Laravel路由地址
type: 'GET',
success: function(response) {
var tableBody = $('#dataTable tbody');
tableBody.empty(); // 清空现有内容
$.each(response, function(index, item) {
tableBody.append(
'<tr>' +
'<td>' + item.id + '</td>' +
'<td>' + item.name + '</td>' +
'<td>' + item.age + '</td>' +
'</tr>'
);
});
},
error: function(xhr, status, error) {
console.error('Error fetching data: ', error);
}
});
});
</script>
</body>
</html>
response()->json($data)
来保证这一点。通过以上步骤,你可以成功地通过AJAX从Laravel Controller获取数组数据并在前端页面上创建一个表格。