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

Ajax fetch()请求中$_GET返回null,PHP变量$categoryName为空致JSON解析错误求助

Troubleshooting Your Q&A Game's PHP/Ajax Issue

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 sends category_name but 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 uses method: 'POST', make sure PHP is using $_POST (not $_GET) to read the value. Also, ensure your fetch request sets the correct Content-Type header:

    • If sending form data:
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      
    • If sending JSON:
      headers: { 'Content-Type': 'application/json' }
      
      And in PHP, you'd need to read the raw input:
      $data = json_decode(file_get_contents('php://input'), true);
      $categoryName = $data['categoryName'] ?? null;
      
  • Guard Against Null Values
    Even if the parameter is missing, don't let $categoryName stay 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:29:37