在服务器端接收AJAX表单数据

问题描述 投票:0回答:1

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

我有以下 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 );  // I am sending this data and want to receive at Server side.

    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');
        }
           
        //more code is here

        return;

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

我的服务器端代码如下。我正在开发一个自定义 WordPress 插件。

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', '' ); // I would like to receive `category_fans` here

       //more code is here
        
    }

    
    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;
    }
}
ajax wordpress forms fetch-api admin-ajax
1个回答
0
投票

如果您的代码一切正确,您只需阅读

$_REQUEST['category_fans']
$_POST['category_fans']
。请问为什么使用 get_class_methods 并循环遍历它们+添加条件,而不是仅添加您希望设置为 Ajax 控制器的方法?

© www.soinside.com 2019 - 2024. All rights reserved.