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 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码