在WordPress中使用Ajax时,为什么在控制台中收到400(错误请求)通知?

时间:2019-02-28 19:43:16

标签: php jquery ajax wordpress

注意,我进入控制台:

POST http://localhost/mysite/wp-admin/admin-ajax.php

  

400(错误请求)

Functions.php:注册JS文件并本地化脚本

function my_scripts_method() {



      wp_register_script('custom_script',
        get_stylesheet_directory_uri()  . '/js/jquery_test.js',
       array('jquery'),
       '1.0' );

      wp_enqueue_script('custom_script');


      wp_localize_script( 'custom_script', 'custom_script_object', array(
            'ajax_url' => admin_url( 'admin-ajax.php' )
        ));

            }
    add_action('wp_enqueue_scripts', 'my_scripts_method');

jquery_test.js文件:

var $j = jQuery.noConflict();

$j(function(){

    $j(".small-board-profile-member").click(function(){

  var fgfdgds =  $j(this).attr('value');
console.log(fgfdgds);


$j('.modal-body').attr('value', fgfdgds);

 $j.ajax({
    url : custom_script_object.ajax_url,
    type : 'post',
    data : {
        post_id : fgfdgds
    },
    processData: false,
    contentType: false,
    success : function( response ) {
        $j('.rml_contents').html(response);
        console.log("it worked");
    }
}); 



  });
});

我的用于处理ajax请求的php函数(放入functions.php中):

add_action( 'wp_ajax_my_action', 'my_action' );

function my_action() {
    global $wpdb; // this is how you get access to the database

    $whatever = ( $_POST['post_id'] );

    //$whatever += 10;

        echo $whatever;

    wp_die(); // this is required to terminate immediately and return a proper response
}

我相信问题出在处理ajax请求的php函数中。非常感谢您的宝贵时间!!!

1 个答案:

答案 0 :(得分:0)

编辑:

在javascript中对此进行更改:

var $j = jQuery.noConflict();

$j(function () {

    $j(".wpb_wrapper").click(function () {

        var fgfdgds = $j(this).attr('value');

        var formData = new FormData();
        formData.append("post_id", 'fgfdgds');
        formData.append("action", 'my_action');


        $j('.modal-body').attr('value', fgfdgds);

        $j.ajax({
            url: custom_script_object.ajax_url,
            type: 'post',
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                $j('.rml_contents').html(response);
                console.log("it worked");
            }
        });



    });
});