向MySQL数据库添加数据时遇JSON解析语法错误求助
Hey, I've run into this exact error dozens of times—let's break down what's going on and fix it step by step.
What's causing this?
This error means your frontend is expecting valid JSON from your backend, but instead it's getting HTML content (like a PHP error message, a warning, or even a full webpage). The < at position 0 is the start of an HTML tag (like <html> or <b>), which breaks the JSON parser completely.
Step 1: See exactly what your backend is returning
First, let's peek at the raw response from your server. Add a complete callback to your AJAX call to log the full response:
$(document).ready(function() { $('form').submit(function(event) { event.preventDefault(); $.ajax({ type: $(this).attr('method'), url: $(this).attr('action'), data: new FormData(this), // Make sure you're passing the form correctly processData: false, // Critical for FormData—don't let jQuery mess with it contentType: false, // Let the browser set the correct multipart header complete: function(xhr) { // Log the raw response to your browser's console (F12 > Console tab) console.log("Raw backend response:", xhr.responseText); }, success: function(response) { // Your existing success logic here }, error: function(xhr, status, error) { console.error("Request failed:", status, error); } }); }); });
When you submit the form, check the console. You'll almost certainly see PHP error messages, HTML, or extra text that's not valid JSON—this is the root problem.
Step 2: Fix your backend PHP to return valid JSON
Your PHP script needs to output only JSON, with no extra whitespace, error messages, or HTML. Here's a template to follow:
// First, turn off direct error output (so errors don't break JSON) ini_set('display_errors', 0); ini_set('log_errors', 1); // Optional: Set a path to log errors if you need to debug later // error_log('/path/to/your/php-error.log'); // Set the correct header to tell the frontend this is JSON header('Content-Type: application/json'); // Connect to your database (replace with your credentials) $conn = mysqli_connect('localhost', 'username', 'password', 'database_name'); // Handle your database insert logic $sql = "INSERT INTO your_table (column1, column2) VALUES ('value1', 'value2')"; $result = mysqli_query($conn, $sql); // Build your response object $response = [ 'success' => $result ? true : false, 'message' => $result ? 'Data added successfully!' : 'Database error: ' . mysqli_error($conn) ]; // Output the JSON and exit immediately (no extra code runs after this) echo json_encode($response); exit;
- No extra output! Make sure there's no whitespace before
<?php, noechostatements for debugging, and no included files that output HTML. - If you need to debug PHP errors, use the error log instead of printing them to the page.
Step 3: Double-check your AJAX settings
Since you're using FormData, these two settings are non-negotiable:
processData: false: Prevents jQuery from converting FormData into a string (which breaks file uploads and form formatting).contentType: false: Lets the browser automatically set the correctmultipart/form-dataheader with a boundary—don't set this manually.
Common mistakes to watch out for
- Accidental whitespace in your PHP file (before
<?phpor after?>). - PHP warnings/errors being printed directly to the page (instead of logged).
- Forgetting to
exitafterecho json_encode()—if code runs after that, it might output extra text.
内容的提问来源于stack exchange,提问作者Iva Kobalava

