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 fastreport怎么判断当前页数
  • ¥15 Kylin-Desktop-V10-GFB-Release-JICAI_02- 2207-Build14-ARM64.iso有没有这个版本的系统啊
  • ¥15 能不能通过蓝牙将传感器数据传送到手机上
  • ¥20 100元python和数据科学实验项目
  • ¥15 根据时间在调用出列表
  • ¥15 R 包chipseeker 安装失败
  • ¥15 Veeam Backup & Replication 9.5 还原问题
  • ¥15 vue-print-nb
  • ¥15 winfrom的datagridview下拉框变成了黑色,渲染不成功
  • ¥20 利用ntfy实现短信推送