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

XAMMP环境下WordPress调用插件类触发JSON解析错误求助

你遇到的JSON解析报错是因为插件类在全局初始化阶段直接输出<script>标签,污染了Gravity Forms的AJAX响应:Gravity Forms添加元素的操作依赖AJAX接口返回纯JSON格式数据,而你输出的<script>标签以<开头,会被JSON解析器当成响应内容的第一个字符,触发解析失败报错。面向过程写法未复现是因为你没有在全局加载阶段直接输出内容,仅OOP写法在实例化时就触发了直接输出。

涉及环境信息

  • 运行环境:XAMPP 7.4.23-0
  • 系统版本:macOS Big Sur 11.6
  • 软件版本:Gravity Forms 2.5.10.1

修复方案

  1. 避免全局初始化阶段直接输出内容,将日志输出行为挂载到WordPress官方指定的资源加载钩子上,仅在正常页面渲染场景输出内容
  2. 增加AJAX请求判断,AJAX请求场景下禁止输出非JSON内容

修复后完整代码

/*
Plugin Name: Testing plugin
Description: filler
Version: 1.0
Author: me
License: GPLv2 or later
Text Domain: plugins testing 
*/

if ( ! defined ( 'ABSPATH')) exit; // Exit if accessed directly

define( 'AGFR__PLUGIN_DIR', plugin_dir_path( __FILE__ ) );

class testing_reporting{
    public function init() {
        // 只在前端非AJAX场景挂载输出,需要后台输出可换成admin_enqueue_scripts钩子
        add_action('wp_enqueue_scripts', [$this, 'output_console_log']);
    }

    public function output_console_log() {
        $this->console_log("Initiating AgfReport class.");
        $this->console_log("AgfReport Short Code initiated.");
    }

    private function console_log($output = null, $with_script_tags = true) {
        // 跳过AJAX请求,避免污染JSON响应
        if($output != null && !wp_doing_ajax()){
            $js_code = 'console.log(' . json_encode($output, JSON_HEX_TAG) . ');';
            if ($with_script_tags) {
                $js_code = '<script>' . $js_code . '</script>';
            }
            echo $js_code;
        }
    }
}

$new_class = new testing_reporting();
$new_class->init();

修复后所有AJAX请求不会再输出额外的script标签,Gravity Forms的JSON响应格式恢复正常,报错会消失。

内容的提问来源于stack exchange,提问作者PlutoTom

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:15:08