如何在视图中展示Ajax请求返回的数据库查询结果的每一行?
Hey there! Let's fix this step by step. The core issue right now is that you're manually encoding your database result to a JSON string in the controller, which makes it hard to loop through on the frontend. Let's adjust both sides to make this work smoothly:
步骤1:修正控制器代码
Laravel's response()->json() automatically converts arrays to valid JSON, so you don't need to manually run json_encode() on your query result. Let's simplify your controller:
public function ajaxRequestPost(Request $request) { $input = $request->all(); $result = DB::select('select * from users'); $ht = "<h3>TESTE</h3>"; // Pass the raw $result array directly - response()->json handles JSON conversion return response()->json(['success' => 'Got Simple Ajax Request.', 'lots' => $result]); }
步骤2:前端遍历并渲染用户数据
Now data.lots in your success callback will be an array of user objects, which you can loop through easily. Let's update the frontend code to render each user's data (I'll use a simple card layout as an example):
$(".btn-submit").click(function(e) { e.preventDefault(); var name = $("input[name=name]").val(); var password = $("input[name=password]").val(); var email = $("input[name=email]").val(); $.ajax({ type: 'POST', url: '/ajaxRequest', data: JSON.stringify({ name: name, password: password, email: email }), dataType: "json", success: function(data) { console.log(data.lots); alert(data.success); // Clear the target container first to avoid duplicate content $("#id").empty(); // Add your TESTE heading $("#id").append("<h3>TESTE</h3>"); // Loop through each user in the returned array $.each(data.lots, function(index, user) { // Build HTML for each user entry const userCard = ` <div class="user-entry" style="margin: 10px 0; padding: 10px; border: 1px solid #eee;"> <p><strong>Name:</strong> ${user.name}</p> <p><strong>Email:</strong> ${user.email}</p> <!-- Add other user fields you need here --> </div> `; // Append the card to your container $("#id").append(userCard); }); } }); });
为什么原来的方法 didn't work?
Your original controller code returned $enc as a JSON string (e.g., "[{\"name\":\"John\",\"email\":\"john@example.com\"}]"), not a native array. While you could fix this by adding JSON.parse(data.lots) in the frontend, letting Laravel handle the JSON conversion is cleaner and avoids extra parsing steps.
If you absolutely need to keep manual encoding in the controller (not recommended), you'd have to parse the string first:
success: function(data) { const users = JSON.parse(data.lots); // Then loop through the users array as above }
内容的提问来源于stack exchange,提问作者Ricardo Barbosa

