duan02143 2018-11-02 18:19
浏览 144
已采纳

WordPress ajax返回404错误请求?

The error is below

POST http://localhost/...../wp-admin/admin-ajax.php 400 (Bad Request)

send @ load-scripts.php?c=1…e,utils&ver=4.9.8:4 ajax @ load-scripts.php?c=1…e,utils&ver=4.9.8:4 (anonymous) @ my-ajax-handler.js?ver=0.1.0:24 i @ load-scripts.php?c=1…e,utils&ver=4.9.8:2 fireWith @ load-scripts.php?c=1…e,utils&ver=4.9.8:2 ready @ load-scripts.php?c=1…e,utils&ver=4.9.8:2
K @ load-scripts.php?c=1…e,utils&ver=4.9.8:2

                $.ajax({
                    type: "POST",
                    url    : my_ajax_handler_var.ajaxurl,
                    
                    data   : {
                         action: 'rc_generate_pa'// "wp_ajax_*" action hook
                    },
                    contentType: "application/json; charset=utf-8",
                    dataType: "json"
                    ,success:function(data) {
                         //This outputs the result of the ajax request
                        var pass = JSON.parse( data );
                        $('#p').val(data);
                        alert( JSON.parse(data));
                    },
                    error: function(errorThrown){
                        console.log(errorThrown);
                    }
                })
//                .done( function( response ) {
//                    var pass = response;
//                    $('#p').val(pass);
//                })
                .fail( function() {
                    console.log("failed");
                });

PHP code for enqueing script and handling request

add_action('admin_enqueue_scripts', 'enqueue_st_page_scripts');
 function enqueue_st_page_scripts() {       
wp_register_script('my-ajax-handler', $plugin_url .'js/my-ajax-handler.js', array('jquery'), '0.1.0', true );
       wp_enqueue_script(array('my-ajax-handler'));
       $vars = array('ajaxurl' => admin_url('admin-ajax.php'));
       wp_localize_script('my-ajax-handler', 'my_ajax_handler_var', $vars); 
   }

    add_action( 'wp_ajax_rc_generate_pa', 'rc_generate_p' );
        function rc_generate_p(){
            $pass = (string)wp_generate_password(8, true, false); 
            echo $pass;
            header('Content-Type: application/json');
            $results = json_encode($pass);
            echo $results;
            exit;
        }    

I have seen similar problems on this site and tried the solution,but no success. I am new to WordPress plugin development.

</div>
  • 写回答

1条回答 默认 最新

  • duanaoyuan7202 2018-11-03 15:45
    关注

    Main Issue

    The problem is in the $.ajax() call, where you should've not set the contentType to JSON:

    $.ajax({
      url: my_ajax_handler_var.ajaxurl,
      contentType: "application/json; charset=utf-8",
      ...
    });
    

    because that way (from the PHP side), the action (i.e. rc_generate_pa) is not available in $_REQUEST['action'] which WordPress uses to determine the AJAX action being called, and when the action is not known, WordPress throws the 400 Bad Request error.

    So to fix the error, just remove the contentType property: (or use something other than the JSON type)

    $.ajax({
      url: my_ajax_handler_var.ajaxurl,
      // Don't set contentType
      ...
    });
    

    Second Issue

    In your $.ajax()'s success callback, don't use the JSON.parse( data ); and here's why:

    1. When dataType is json, jQuery will automatically parse the response output into a JSON object — or it could also be a string; see point #2 below.

    2. In the (PHP) rc_generate_p() function, the $pass is neither an array nor object/class; hence in the $.ajax()'s success callback, the data is actually an invalid JSON string and JSON.parse( data ) will throw a JavaScript syntax error.

    So your $.ajax()'s success could be rewritten into:

    success: function(data){
      $('#p').val(data);
      console.log(typeof data); // test
    })
    

    Third Issue

    In your rc_generate_p() function, remove the echo $pass;, or you'll get a JavaScript syntax error — your AJAX call is expecting a JSON response, and yet that echo part invalidates the JSON.

    I know you probably added that to debug the 400 error; but I thought I should just remind you about removing it.. :)

    And you might want to consider using wp_send_json() like so, where you don't need to call exit, die, or wp_die():

    function rc_generate_p() {
      $pass = wp_generate_password( 8 );
      wp_send_json( $pass );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵