jQuery.Deferred异常:JSON解析错误求助(附完整代码)
Hey there! Let's break down what's causing that error and fix it step by step.
What's the root problem?
The error Unexpected token < in JSON at position 0 means the data coming back from your comment_insert.php isn't valid JSON. Instead, it's probably HTML content—like a PHP error message, a warning, or an accidental HTML tag that starts with <. When jQuery.parseJSON() tries to parse that HTML as JSON, it breaks immediately.
Step 1: Debug the server response first
First, let's see exactly what the server is sending back. Update your frontend code to log the full response in the error case:
$.post("comment_insert.php" , { task : "comment_insert", userId : _userId, comment : _comment } ) .catch(function(jqXHR, textStatus, errorThrown) { // Log the raw server response to see what's wrong console.log("Server returned this instead of JSON:", jqXHR.responseText); console.log("Error details:", textStatus, errorThrown); }) .then(function(data) { comment_insert(jQuery.parseJSON(data)); console.log("ResponseText: " + data); });
Run this and check your browser console—you'll likely see a PHP error message (like a missing database connection, syntax error, or unclosed tag) printed as HTML. Fix those PHP issues first!
Step 2: Fix the server-side (comment_insert.php)
Make sure your PHP script only outputs valid JSON, with no extra content (no debug echo statements, no HTML, no whitespace before <?php). Here's a minimal, safe example:
<?php // Set the correct content type for JSON header('Content-Type: application/json'); // Handle the comment insert request if ($_POST['task'] === 'comment_insert') { $userId = $_POST['userId']; $comment = $_POST['comment']; $userName = $_POST['userName']; // Pass this from frontend or fetch from DB // 👉 Replace this with your actual database insert logic // Assume we successfully inserted the comment and got these values $response = [ 'comment_id' => uniqid(), // Use real ID from DB 'profile_img' => 'path/to/default-avatar.jpg', // Real user avatar path 'userName' => $userName, 'comment' => $comment ]; // Output only JSON echo json_encode($response); exit; } else { echo json_encode(['error' => 'Invalid task']); exit; } ?>
- Never output anything before
header('Content-Type: application/json');(even accidental whitespace will break JSON). - Use
json_encode()to generate valid JSON—don't manually stringify it.
Step 3: Clean up the frontend code
We can make the frontend more robust and fix small bugs:
- Let jQuery auto-parse JSON by adding
'json'as the 4th parameter to$.post(no need forjQuery.parseJSON()anymore). - Fix a stray
</div>in yourcomment_insertfunction that breaks DOM structure. - Remove the random
nin your comment text (it would display as a literal "n" instead of a newline—use<br>if you want line breaks).
Here's the updated frontend code:
$( document ).ready( function(){ $( '#comment-post-btn' ).click( function(){ comment_post_btn_click(); }); }); function comment_post_btn_click(){ var _comment = $( '#comment-post-text').val(); var _userId = $( '#userId').val(); var _userName = $( '#userName').val(); if( _comment.length > 0 && _userId != null){ $('.comment-insert-container').css('border' , '1px solid #e1e1e1'); // Let jQuery auto-parse JSON by adding 'json' as the 4th argument $.post("comment_insert.php" , { task : "comment_insert", userId : _userId, comment : _comment }, 'json') .catch(function(jqXHR, textStatus, errorThrown) { console.log("Error:", textStatus); console.log("Server response:", jqXHR.responseText); }) .then(function(data) { comment_insert(data); // No need for parseJSON now! console.log("Response data:", data); }); console.log(_comment + " Username: " + _userName + " User Id:" + _userId); } else{ $('.comment-insert-container').css('border' , '1px solid #ff0000'); console.log("The text area was empty"); } $( '#comment-post-text').val(""); } function comment_insert(data){ var t = ''; t += '<li class="comment-holder" id="_'+data.comment_id+'">'; t += '<div class="user-img">'; t += '<img src="'+data.profile_img+'" class="user-img-pic"/>'; t += '</div>'; t += '<div class="comment-body">'; t += '<h3 class="username-field">'+data.userName+'</h3>'; t += '<div class="comment-text">'+data.comment+'</div>'; // Fixed stray "n" here t += '</div>'; // Removed extra </div> that was breaking DOM t += '<div class="comment-buttons-holder">'; t += '<ul>'; t += '<li class="delete-btn">X</li>'; t += '</ul>'; t += '</div>'; t += '</li>'; $('.comments-holder-ul').prepend( t ); }
Final Checks
- Run your code again and check the console—if the server is now returning valid JSON, the error should disappear.
- Make sure your PHP script doesn't have any syntax errors (use
php -l comment_insert.phpin the terminal to check). - Ensure all variables used in
comment_insert.php(like database connections) are properly set up.
内容的提问来源于stack exchange,提问作者fehmiE

