Ajax fetch()请求中$_GET返回null,PHP变量$categoryName为空致JSON解析错误求助
Hey there, let's work through fixing this problem where your $categoryName variable is null in PHP, causing that frustrating JSON parse error in your JS fetch call. Here's a step-by-step breakdown of what to check and fix:
First: Diagnose Why $categoryName Is Null in PHP
The root cause of your JSON error is almost certainly that PHP is outputting invalid content (like error notices) instead of clean JSON, because $categoryName isn't being set correctly. Let's fix that first:
Verify Request Parameter Matching
Double-check that the parameter name your JS is sending matches exactly what PHP is trying to read. For example, if your fetch sendscategory_namebut PHP uses$_POST['categoryName'], you'll get null. Add a debug line at the top of your PHP file to see all incoming parameters:var_dump($_REQUEST); // This will show all GET/POST parameters exit;Run your fetch call and check the response—you'll see if your category name is actually being sent.
Confirm Request Method & Content-Type
If your fetch usesmethod: 'POST', make sure PHP is using$_POST(not$_GET) to read the value. Also, ensure your fetch request sets the correctContent-Typeheader:- If sending form data:
headers: { 'Content-Type': 'application/x-www-form-urlencoded' } - If sending JSON:
And in PHP, you'd need to read the raw input:headers: { 'Content-Type': 'application/json' }$data = json_decode(file_get_contents('php://input'), true); $categoryName = $data['categoryName'] ?? null;
- If sending form data:
Guard Against Null Values
Even if the parameter is missing, don't let$categoryNamestay null without handling it. Explicitly set a default and return a valid JSON error response instead of letting PHP output warnings:header('Content-Type: application/json'); // Always set this first $categoryName = $_POST['categoryName'] ?? null; if (!$categoryName) { echo json_encode(['error' => 'Category name parameter is missing']); exit; // Stop execution here } // Your existing logic here... echo json_encode(['success' => true, 'data' => 'Your response content']);
Fix the JSON Parse Error in JavaScript
Once PHP is returning valid JSON (even error responses), your fetch call will stop throwing that syntax error. Update your JS to handle both success and error cases properly:
fetch('your-php-file.php', { method: 'POST', body: new URLSearchParams({ categoryName: 'your-selected-category' }), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(result => { if (result.error) { console.error('Server error:', result.error); // Show an error message to the user here return; } // Handle your valid game data here console.log('Received data:', result.data); }) .catch(error => { console.error('Fetch error:', error); });
Quick AMPPS Server Check
Make sure AMPPS isn't outputting extra content that breaks your JSON:
- Disable PHP's display_errors setting (in AMPPS PHP config) to prevent warning messages from being added to your JSON response. You can also add
error_reporting(0);at the top of your PHP file temporarily for testing.
By fixing the $categoryName null issue first and ensuring PHP only outputs valid JSON, that parse error in your JS will disappear, letting you get back to building your game!
内容的提问来源于stack exchange,提问作者Luke Theuma

