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

如何在WordPress插件服务端接收Fetch API发送的AJAX表单数据?

如何在服务端接收由Fetch API发送的AJAX表单数据?

我正在开发自定义WordPress插件,前端用Fetch API发送FormData,希望在服务端接收category_fans字段,相关代码如下:

前端Fetch API代码

const sent_urls = () => {
    const formData = new FormData();
    formData.append('action', 'start_parsing');
    formData.append('of_start_parsing_nonce', of_start_parsing_nonce.value);
    formData.append('urls', urls.slice(offset, offset + limit));

    formData.append( 'category_fans', category_fans );  // 发送该数据,需在服务端接收

    fetch(ajaxurl, {
        method: 'POST',
        body: formData
    }).then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    }).then(data => {
        if (data.error) {
            throw new Error(data.error);
        }

        if (!data.result) {
            throw new Error('Unknown error');
        }
           
        // 更多代码在此

        return;

        } else {
            sent_urls();
        }
    }).catch(error => {
        enable();
        alert.show_warn(error);
    });
}

服务端代码

use function get_class_methods;


class AdminAjax {
    
    public function __construct() {
        $this->register_actions();
    }

    
    public function start_parsing() {

        if ( ! $this->verify( 'start_parsing' ) ) {
            echo wp_json_encode(
                array(
                    'error' => 'Error request.',
                )
            );
            wp_die();
        }

        $category = $this->get_post_field( 'category_fans', '' ); // 在此接收`category_fans`

       // 更多代码在此
        
    }

    
    public static function get_nonce_field( string $action_name ) {
        wp_nonce_field( "of_{$action_name}_action", "of_{$action_name}_nonce" );
    }

    
    private function register_actions() {
        $methods = get_class_methods( $this );

        foreach ( $methods as $method ) {
            if ( '_' === substr( $method, 0, 1 ) ) {
                continue;
            }

            if ( 'register_actions' === $method ) {
                continue;
            }

            add_action( 'wp_ajax_' . $method, array( $this, $method ) );
            add_action( 'wp_ajax_nopriv_' . $method, array( $this, $method ) );
        }
    }


    private function verify( string $action_name ): bool {
        $nonce  = "of_{$action_name}_nonce";
        $action = "of_{$action_name}_action";

        return isset( $_POST[ $nonce ] ) && wp_verify_nonce( $_POST[ $nonce ], $action );
    }

    
    private function get_post_field( string $key, $default = '' ) {
        return isset( $_POST[ $key ] ) ? wp_unslash( $_POST[ $key ] ) : $default;
    }
}

解决方案

你的代码已经具备接收category_fans的能力,只需确认以下几点:

  1. 数据格式匹配:如果category_fans是数组类型,前端需要以category_fans[]为键循环添加数据,比如:

    category_fans.forEach(item => {
        formData.append('category_fans[]', item);
    });
    

    服务端则可以通过$category = $this->get_post_field('category_fans', array());获取数组。如果是普通字符串或数字,当前写法直接可用。

  2. 验证数据是否到达:若接收不到数据,可按以下步骤排查:

    • 前端发送前打印console.log(formData.get('category_fans')),确认数据已添加到FormData;
    • 服务端在start_parsing方法开头添加error_log(print_r($_POST, true));,查看服务器日志确认category_fans是否存在于$_POST数组中;
    • 检查nonce验证是否通过,若验证失败会直接返回错误,后续代码不会执行。
  3. 直接使用获取到的数据:当前服务端代码中$category变量已经存储了category_fans的值,可直接在后续逻辑中使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 01:15:06