jQuery Ajax拒绝发送POST请求,始终发送GET请求求助
Hey there, let's troubleshoot why your Ajax POST request isn't working with that button—since other POST requests are fine, we can focus on specific, common pitfalls in your setup.
First: Fix Your HTML Syntax
Looking at the button code you shared, there's a critical syntax error that's probably breaking your DOM structure (and thus preventing event binding):
Your <button> tag isn't closed, and the nesting is off. Correct it to:
<div class="row"> <div class="col-sm-4 col-sm-offset-4"> <div class="form-group"> <button type="button" id="btn-save" class="btn btn-success btn-block btn-lg">Save &...</button> </div> </div> </div>
Notice I added type="button" too—this prevents the button from acting as a submit button (which would trigger a full page reload and cancel your Ajax request if it's inside a form).
Second: Ensure Proper Event Binding & Ajax Setup
Since jQuery is included in app.js, make sure you're binding the click event correctly, and handling Laravel's CSRF protection (a super common gotcha):
- Add CSRF Token Meta Tag
Put this in your blade template's<head>section:
<meta name="csrf-token" content="{{ csrf_token() }}">
- Bind the Click Event & Configure Ajax
Add this to your JS (either inapp.jsor a separate script tag, wrapped in a DOM-ready handler):
$(document).ready(function() { // Set up CSRF header for all Ajax requests $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); // Bind click event to your button $('#btn-save').on('click', function() { // Example Ajax POST request $.ajax({ url: '/your-endpoint', // Replace with your actual Laravel route method: 'POST', data: { // Add your form data here, e.g.: name: $('input[name="name"]').val() }, success: function(response) { console.log('Success:', response); // Handle success response }, error: function(xhr) { console.error('Error:', xhr.responseText); // Handle error } }); }); });
Third: Debug with Browser Dev Tools
If it's still not working, open your browser's Developer Tools (F12):
- Check the Console tab for JavaScript errors (e.g., unbound elements, missing CSRF token)
- Go to the Network tab, click the button, and see if the Ajax request even fires. If it does, check the request/response details for Laravel-specific errors (like 419 CSRF mismatch, 404 route not found).
Final Checks
- Verify your Laravel route is defined correctly in
routes/web.php(make sure it's aPOSTroute) - If your button is loaded dynamically (e.g., via another Ajax call), use delegated event binding:
$(document).on('click', '#btn-save', function() { // Same Ajax code as above });
内容的提问来源于stack exchange,提问作者Peter Griffin

