WordPress插件开发admin-ajax.php 400(错误请求)

时间:2020-03-31 15:33:36

标签: php ajax wordpress

大家好,我正在尝试在自定义插件中使用Ajax进行wordpress,但是控制台出现问题,显示admin-ajax中的400错误请求

  1. JS脚本

    public static function register_script(){
    
        wp_enqueue_script('ajaxscript', substr(plugin_dir_url(__FILE__), 0, -10) . '/assets/js/register-post.js', array( 'jquery', 'json2' ), '1.0.0', true );
    
        wp_localize_script( 'ajaxscript', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ),'nonce' => wp_create_nonce('ajaxnonce') ) );
    
    }
    
    1. Ajax

function signup(){
  // alert("working");

  jQuery('#registration').on('submit', function(e) {
    var data =  jQuery("#registration").serialize();
    e.preventDefault();
    // e.stopPropagation(); // only neccessary if something above is listening to the (default-)event too

      jQuery.ajax({
          type: 'POST',
          url: my_ajax_object.ajax_url,
          processData: false,
          data: {
            action: 'register_ajax_request&nonce='+ my_ajax_object.nonce,
            data: data
          },
          dataType: 'json',
          success: function(response) {
          if(response.success === true) {
               // jQuery("#vote_counter").html(response.vote_count)
            }else {
               // alert("Your vote could not be added")
            }
          }
          
        });   
      
    });
          
  }

  1. 注册功能

<?php
add_action('wp_ajax_register_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_nopriv_register_ajax_request', 'ajax_handle_request');


function ajax_handle_request(){

	if (isset($_POST['register_trigger'])){

		$nonce = $_POST['nonce']; 
		print_r($nonce);
		exit();
	}
}

registration.php的位置是plugindirectory / inc / pages /。这不是像wordpress主题那样的function.php。

enter image description here enter image description here

1 个答案:

答案 0 :(得分:0)

对不起,我只是忘记包含该操作正在寻找的php文件。