Laravel中Ajax请求报错:无法设置正确URL的问题求助
Hey there, let's work through this Ajax problem together—totally get how frustrating it is when a basic feature won't cooperate after hours of digging. Looking at your code, I spot a few key areas that might be throwing things off:
1. Incomplete CSRF Token Configuration
Your $.ajaxSetup code cuts off, and if you're using a framework like Laravel (judging by your route structure), missing or incorrect CSRF token handling is the #1 culprit for blocked POST requests.
First, make sure your HTML has a meta tag for the CSRF token:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then complete the ajaxSetup block, and place it before your form submit handler so it applies to all Ajax requests:
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
2. Event Binding Timing
If your script runs before the DOM fully loads, $('#counter').submit(...) won't find the form element, meaning the event never gets bound. Wrap your code in $(document).ready() to fix this:
$(document).ready(function() { // Your form submit handler and ajaxSetup go here });
3. Redundant Form Selector & Error Handling
You can clean up the data line by using $(this).serialize() (since this refers to the submitted form inside the handler), and add a .fail() callback to catch errors—this is critical for debugging why the request isn't working:
$('#counter').submit(function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: '/games/question/update', data: $(this).serialize(), // More concise and reliable dataType: 'json' }).done(function(data) { console.log(data); }).fail(function(xhr, status, error) { // Log errors to debug issues like 419 (CSRF) or 500 (server) errors console.error('Ajax failed:', error); console.log('Server response:', xhr.responseText); }); });
Quick Debug Check
First test if event.preventDefault() is even working: add console.log('Form submit triggered!') right after event.preventDefault();. If you don't see this in the console, your event handler isn't binding—double-check your form's id is actually counter, and that your script loads after the form in the DOM.
内容的提问来源于stack exchange,提问作者Brecherchef

