Laravel中Ajax请求返回空JSON对象问题求助
Troubleshooting Empty JSON Response in Laravel Ajax POST Request
Hey there! Let's break down why your Ajax request is returning an empty JSON response and fix it step by step.
1. The Root Cause: Incorrectly Serializing the Request Object
Your current route code returns the entire Request object directly to response()->json(), but Laravel's Request class isn't designed to be serialized into JSON like a simple array. This is why you're getting an empty response— the serializer can't access the request data properly from the object itself.
2. Fixed Route Code
Update your route to extract the actual request data using $request->all() (to get all submitted data) or $request->input('test') (to get a specific field):
use Illuminate\Http\Request; Route::post('testSend', function (Request $request) { // Return all submitted data as JSON return response()->json($request->all()); // OR, return only the 'test' field if you prefer // return response()->json(['test_value' => $request->input('test')]); })->name('testSend'); // Add a route name for easier URL generation
3. Improvements to Your Ajax Code
There are two small tweaks here to make things more reliable:
- Use Laravel's route helper to generate the correct URL (avoids path issues if your app is in a subdirectory or uses route prefixes)
- Fix the alert to display the JSON properly (alerting an object directly will just show
[object Object])
Updated JavaScript:
$(document).ready(function () { $('#btn').on('click', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{{ route('testSend') }}', // Use named route for accurate URL data: { test: 'hello' }, dataType: 'json', success: function (response) { console.log('Received response:', response); // Better to inspect in console alert(JSON.stringify(response)); // Convert object to string for readable alert }, error: function (data) { console.log('Error:', data); } }); }); });
4. Quick Checks to Verify
- In Chrome DevTools' Network tab, check the Request Payload section of your Ajax call to confirm
test=hellois being sent. - Verify the
X-CSRF-TOKENheader is present in the request headers (your current setup for this looks correct, but it's good to double-check). - Ensure your route is correctly registered (run
php artisan route:listin your terminal to confirm thetestSendPOST route exists).
内容的提问来源于stack exchange,提问作者Sysptn
相关产品推荐
相关产品推荐

