WP ajax功能

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

我在项目中进行 AJAX 调用时遇到 400 错误。我知道这个问题被问了很多次,但我无法弄清楚我的问题。

这是我的 JavaScript 代码:

function uploadFile() {
    jQuery.ajax({
        url: ajax.url,
        type: 'POST',
        data: {
            'action': 'excel_converter',
            'id': 'test'
        },
        processData: false,
        success: function(response){
            console.log('response', response);
        }
    });
}

jQuery(() => {
    const converter = jQuery('.js-excel-converter');
    if(converter) {
        converter.on('click', (e) => {
            e.preventDefault();
            uploadFile();
        });
    }
});

这是我的PHP代码(在functions.php中):

function excel_converter() {
    echo 'hi';
    die('test');
}

function my_script_enqueuer() {
    $manifest = json_decode(file_get_contents(get_template_directory() . '/dist/rev-manifest.json'), true);
    $jsFile = $manifest['app.bundle.full.js'];

    wp_enqueue_script( 'ajax-js', get_template_directory_uri() . '/dist/scripts/' . $jsFile, array('jquery') );

    // You can now use ajax.url as the URL in your ajax calls
    wp_localize_script( 'ajax-js', 'ajax', array(
        'url' => admin_url( 'admin-ajax.php' )
    ));

    add_action( 'wp_ajax_excel_converter', 'excel_converter' );
    add_action( 'wp_ajax_nopriv_excel_converter', 'excel_converter' );
}
add_action( 'init', 'my_script_enqueuer' );

php 代码似乎工作正常,因为我可以使用 ajax.url 作为我的 Post url。 但由于某种原因,我不断收到请求 url http://localhost:3000/wp-admin/admin-ajax.php 的 400。我用我的本地域尝试过,但结果相同; http://mysite.test/wp-admin/admin-ajax.php

php jquery ajax wordpress
1个回答
0
投票

processData
设为
false
可防止您的数据转换为
application/x-www-form-urlencoded
,如果没有此转换,wordpress 将不知道为您的 ajax 请求采用
action

在 ajax 调用中删除

processData: false,

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