Laravel中Ajax无法提交至控制器问题求助
Troubleshooting Your Dynamic Submenu Ajax Issue
Let's work through this step by step—there are a few clear issues in your code that are likely stopping your Ajax call from firing, which is why your controller's sub method never runs.
1. Fix the Critical Syntax Error in Your Ajax Code
Looking at your JavaScript, there's a missing comma and closing brace in the data object. This invalid syntax will cause a JavaScript error, preventing the Ajax request from being sent at all.
Broken code:
data: {"main_menu_id": main_menu_id,_token: '{{csrf_token()}}'
Fixed code:
data: { "main_menu_id": main_menu_id, _token: '{{csrf_token()}}' },
Pro tip: Always check your browser's console (F12 → Console tab) for JavaScript errors—this would have shown you the syntax issue immediately.
2. Verify Your Route Configuration (Laravel 8+)
If you're using Laravel 8 or newer, your route definition needs to reference the controller class correctly. Make sure you either import the controller at the top of your routes/web.php file:
use App\Http\Controllers\TicketController; Route::post('/sub', [TicketController::class, 'sub']);
Or use the full namespace in the route:
Route::post('/sub', [\App\Http\Controllers\TicketController::class, 'sub']);
Older Laravel versions allowed the shorthand Route::post('/sub','TicketController@sub');, but this is deprecated in newer releases.
3. Ensure CSRF Token is Properly Handled
While you included the _token in your Ajax data, double-check that the Blade directive {{csrf_token()}} is rendering correctly. View your page source—if you see the literal text {{csrf_token()}} instead of a long token string, you're probably using this JavaScript in an external .js file (where Blade directives don't work).
Fix this by adding a meta tag to your Blade layout:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then update your Ajax code to pull the token from the meta tag:
_token: $('meta[name="csrf-token"]').attr('content')
4. Debug the Controller and Request
To confirm if your request is even reaching the controller, add logging to your sub method:
use Illuminate\Support\Facades\Log; public function sub(Request $request) { // Log the incoming request to verify it arrives Log::info('Submenu request received', $request->all()); $submenus = DB::connection("mysql2") ->table('applicationsubmenu') ->join('applicationmenu', 'applicationmenu.Id', '=', 'applicationsubmenu.ApplicationMenuId') ->select('applicationsubmenu.*') ->where('applicationmenu.MainMenuId', '=', $request->main_menu_id) ->get() ->toArray(); // Use Laravel's json response helper for consistency return response()->json([ 'submenus' => $submenus ]); }
Check your storage/logs/laravel.log file—if you see the log entry, the request is reaching the controller. If not, the issue is still with the frontend or route.
5. Improve Frontend Error Feedback
Your current error callback doesn't give useful info. Update it to log details about the failure:
error: function (xhr, status, error) { console.log('Request Status:', status); console.log('Error Details:', error); console.log('Server Response:', xhr.responseText); alert('Failed to load submenus: ' + error); }
This will tell you if you're getting a 404 (route not found), 419 (CSRF token mismatch), or 500 (server error) response.
6. Clean Up Submenu Options Before Appending
Right now, every time you change the main menu, you'll append new options to the existing ones. Add $('#submenu').empty(); before your loop to clear old entries:
success: function (data) { $('#submenu').empty(); // Clear old options first var submenus = data.submenus; for(var i=0; i<submenus.length; i++){ // Use actual fields from your submenu (adjust based on your database columns) $('#submenu').append('<option value="'+submenus[i].Id+'">'+submenus[i].Name+'</option>'); } }
Since you're returning full submenu objects, you need to reference specific fields (like Id and Name) instead of just submenus[i], which would display [object Object].
内容的提问来源于stack exchange,提问作者RandomUser

