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

Laravel中Ajax请求报错:无法设置正确URL的问题求助

Troubleshooting Your Ajax Form Submission Issue

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:55:45