dongyan3853 2019-02-28 19:43
浏览 173

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

Notice I'm getting in the console:

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

400 (Bad Request)

Functions.php: register JS file and localize script

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 file:

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");
    }
}); 



  });
});

My php function to handle the ajax request (put in 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
}

I believe the problem is in the php function to handle the ajax request. Thank-you very much for your time!!!

  • 写回答

1条回答 默认 最新

  • dongxin2734 2019-02-28 19:58
    关注

    edit:

    change this in 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");
                }
            });
    
    
    
        });
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制