WP Ajax 400错误的请求。 Ajax的类和方法

时间:2019-06-26 11:36:26

标签: php ajax wordpress

我是 OOP PHP 的新手,所以这可能是我出问题的地方。

这是我的简单课程。当我加载页面时,它将被调用,并且其他jQuery可以很好地发送ajax请求。

编辑: 我在woocommerce帐户页面中创建了一个新标签。 (knp_product_submission_content)。这会吐出一些基本的HTML。 当用户单击页面上的图标时,来自表单的数据将通过ajax提交(仅是动作输入的值)。然后,这应该从回调中返回内容。

/**************
Add the core js file in the main plugin file. 
*********************/
function knp_vendor_scripts(){  
    wp_enqueue_script( 'core', plugin_dir_url(__FILE__).'js/core.js', array(), false, true );
    wp_localize_script('core', 'vendor_ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));

}
add_action( 'wp_enqueue_scripts', 'knp_vendor_scripts' );

/**
* New class initiated in a woocommerce endpoint function
**/
function knp_product_submissions_content(){ 

  //Create the views object for fetching and displaying. 
  $views = new submission_views();         
  echo '<div class="ajax-container-div">';
     //response content should go here      
  echo '</div>';

}
add_action('woocommerce_account_product-submissions_endpoint', 'knp_product_submissions_content');

/**
* Get the data from the form
* the user has just clicked on
*/
jQuery(document).ready(function(){

    jQuery('.knpv_form_submit').on('click', function(){

    var formID = 
    jQuery(this).closest('form.knpv_ajax_form').attr('id');

    var data = jQuery('#'+formID).serialize();

    jQuery.post(vendor_ajax_object.ajax_url, data, function(response) {

        jQuery('.ajax-container-div').html(response);

    });

  });

});

class submission_views{
    /**
    * Setup ajax action and callbacks
    */
    public function __construct(){
        //Get the form for a new submission
        add_action('wp_ajax_knpv_add_new_submission', array($this, 'knpv_add_new_submission_callback'));
        add_action('wp_ajax_nopriv_knpv_add_new_submission', array($this, 'knpv_add_new_submission_callback'));
    }

    /**
    * Get the form html and send back 
    */ 
    public function knpv_add_new_submission_callback(){ 
        ob_start(); 
        ?>

        <section class="knp_vendor_submission_form">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <?php echo do_shortcode('[gravityform id=3'); ?>
                    </div>
                </div>
            </div>
        </section>

        <?php 
        $content = ob_get_clean();
        return $content;
    }

我实际上是在替换页面上的某些内容。点击触发它,我得到的回复是

  

400错误的请求

我将add_action放在正确的位置吗?我怎么知道它是否甚至看到了回调函数?

TIA

1 个答案:

答案 0 :(得分:1)

您创建了该类,但没有为此创建对象!请在您的主插件文件中插入以下行:

$ajax_handlers = new submission_views();