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 );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站