WordPress:Ajax请求记录了400错误的控制台请求 [英] Wordpress: Ajax request logs 400 Bad Request to console

查看:130
本文介绍了WordPress:Ajax请求记录了400错误的控制台请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不断收到此错误:

POST http://localhost/wptest2/wp-admin/admin-ajax.php 400 (Bad Request)
(anonymous) @ VM12565:1
send @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:4
ajax @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:4
(anonymous) @ options-general.php?page=fvc-settings:784
dispatch @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:3
r.handle @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:3

  1. 在下面的代码中,ajaxPost()挂接到了我的管理页脚 插入.
  2. 单击jQuery选择的按钮后,它将触发已注册的帖子请求并返回简单的响应.
  1. In the code below, ajaxPost() is hooked to the admin footer of my plugin.
  2. On clicking the button selected by jQuery, it should fire the registered post request and return a simple response.

这不是jQuery.post()或$ .ajax()发生的情况.我尝试了以下注释中提到的几件事,但无法正常工作,有人可以告诉问题吗?

This is not what happens with jQuery.post() or $.ajax(). I tried several things mentioned below in the comments but can't get it working, can anyone tell the issue?

function ajaxPost() {
  ?>

  <script>     
    jQuery(document).ready(function($) {        
      $('#previousButton').click(function() {
        var postData = {
          action : 'selectTargetsWithOffset',
          data : {
            offsetMultiplier : 1,
            incrementSize : 10
          },
          success : function(response) {
            console.log(`=====jQuery success=====`);
          }
        };

        var handleResponse = function(response) {
          console.log(response, `=====response=====`);
        };

        jQuery.post(ajaxurl, postData, handleResponse);

        // this code also threw a 400 error when 
        // I commented out the above code instead
        // $.ajax({
        //   type: "POST",
        //   url: ajaxurl,
        //   dataType: "json",
        //   data: {
        //     action: "selectTargetsWithOffset",
        //   },
        //   success: function() {
        //     console.log(response, `=====response 
        //       from $.ajax}=====`);
        //   }
        // });

      })

    })
  </script>
  <?php
}
add_action('admin_footer', 'ajaxPost');


function selectTargetsWithOffset() {
  wp_send_json([ 'message' => 'from back end' ]);
  wp_die();
}
add_action('wp_ajax_selectTargetsWithOffset', 'selectTargetsWithOffset');

也尝试过 -进入admin-ajax.php并将响应代码从400更改为420,以查看它是否可以执行任何操作.我确实收到了一些反映更改的奇怪错误.

Also tried - Going into admin-ajax.php and changing the response code from 400 to 420 to see if it would do anything. I did get some wierd error reflecting the change.

if ( is_user_logged_in() ) {
// If no action is registered, return a Bad Request response.
if ( ! has_action( "wp_ajax_{$action}" ) ) {
    wp_die( 'Test', 420 );
}

  • 将wp_die()的arg1中的"0"更改为测试",然后在浏览器中访问此URL: http://localhost/wptest2/wp-admin/admin-ajax.php .我仍然在该地址的页面上(单独)看到0渲染
    • Changing '0' in arg1 of wp_die() to "Test" and visiting this url in the browser: http://localhost/wptest2/wp-admin/admin-ajax.php . I still see 0 rendered on the page (alone) at this address
    • 在admin-ajax.php的顶部添加以下内容:

      Adding the following to the top of admin-ajax.php:

        ?>
          <script>
            console.log(`=====TEST=====`);
            var request = "<?php echo $_REQUEST ?>";
            console.log(request['action'], `=====request=====`);
          </script>
        <?php
      

      当我尝试在管理区域中触发ajax调用时,我仍然仅收到400错误响应控制台日志.但是,当我直接导航到URL时,现在我看到=== TEST ===语句,并且请求被标记为未定义(正如我期望的那样).我认为这意味着我如何称呼ajax请求是错误的.

      When I try to trigger the ajax call in my admin area, I still get the 400 bad response console log only. However when I directly navigate to the URL, now I see the ===TEST=== statement and request is marked as undefined (as I would expect). I take this to mean something about how I call the ajax request is wrong.

      这是我进行呼叫的按钮的HTML代码:

      Here is my HTML code for the button that does the call:

      <button id="previousButton">Previous</button>
      


      针对简化的回调建议

      这是控制台日志:


      In response to the simplified callback suggestion

      Here is the console log:

      =====jQuery success=====
      VM13659:1 POST http://localhost/wptest2/wp-admin/admin-ajax.php 400 (Bad Request)
      (anonymous) @ VM13659:1
      send @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:4
      ajax @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:4
      n.(anonymous function) @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:4
      (anonymous) @ options-general.php?page=fvc-settings:785
      dispatch @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:3
      r.handle @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:3
      

      这是代码:

      function ajaxPost() {
        ?>
        <script>
      
          jQuery(document).ready(function() {
            jQuery('#previousButton').click(function() {
      
              var postData = {
                action : 'selectTargetsWithOffset',
                data : {
                  offsetMultiplier : 1,
                  incrementSize : 10
                },
                success : function(response) {
                  console.log(`=====jQuery success=====`);
                }
              };
      
              var handleResponse = function(response) {
                console.log(response, `=====response=====`);
              };
      
              jQuery.post(ajaxurl, postData, handleResponse);
            }); 
          })
        </script>
        <?php
      }
      add_action('admin_footer', 'ajaxPost');
      
      
      function selectTargetsWithOffsetcb() {
        print_r($_POST);
        die();
      }
      
      add_action( 'wp_ajax_selectTargetsWithOffset', "selectTargetsWithOffsetcb");
      add_action( 'wp_ajax_nopriv_selectTargetsWithOffset', "selectTargetsWithOffsetcb" );
      

      页面本身没有输出print_r(),它保持不变而没有任何刷新

      There is no print_r() output on the page itself, it stays the same without any refreshing

      再次值得注意的是,admin-ajax.php中的调试代码====TEST===无法登录.我认为这表明请求由于某种原因未到达该文件(因为在浏览器中导航到该文件确实会导致该日志记录到控制台)

      It is worth noting again that the debug code ====TEST=== in admin-ajax.php failed to log. I think this indicates the request doesn't reach that file for some reason (since navigating to that file in browser does cause it to log to console)

      也尝试过此操作,但也出现400错误:

      Also tried this, but also a 400 error:

      function ajaxPost() {
        ?>
        <script>    
          jQuery(document).ready(function() {
           jQuery(document).on("click","#previousButton", function() {
             jQuery.ajax({
               url: "<?php echo admin_url( 'admin-ajax.php' ) ?>",
               data: {"action":"selectTargetsWithOffset","datas": {"name": "yourfields"}},
               type:"post",
               success: function(data) { alert(data); }
             })
           });    
          })
        </script>
        <?php
      }
      add_action('admin_footer', 'ajaxPost');
      

      推荐答案

      我认为您尚未在插件或函数文件中声明回调函数.

      I think you have not declared callback functions in your plugin or function file.

      请在您的插件或fn文件中添加以下代码,然后对其进行测试.

      Please add below code to your plugin or fn file and test it.

      add_action( 'wp_ajax_selectTargetsWithOffset', "selectTargetsWithOffsetcb");
      add_action( 'wp_ajax_nopriv_selectTargetsWithOffset', "selectTargetsWithOffsetcb" );
      
      function selectTargetsWithOffsetcb()
      {
      
          print_r($_POST);
          die();
      }
      

      还要更新此js

          <script>
      jQuery(document).on("click","#previousButton",function(){
      
      jQuery.ajax({
      url:"<?php echo admin_url( 'admin-ajax.php' ) ?>",
      data:{"action":"selectTargetsWithOffset","datas":{"name":"yourfields"}},
      type:"post",
      success:function(data){alert(data);}
      })
      });
      </script>
      

      这篇关于WordPress:Ajax请求记录了400错误的控制台请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆