You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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=hello is being sent.
  • Verify the X-CSRF-TOKEN header 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:list in your terminal to confirm the testSend POST route exists).

内容的提问来源于stack exchange,提问作者Sysptn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:30:07