我试图在插件的类中调用ajax函数。但控制台在url/wp-admin/admin-ajax.php上显示400错误
我尝试在构造函数和函数中添加ajax钩子(如下所示),但都不起作用。但是在类之外,PHP ajax函数可以按预期工作。
(我对插件开发和OOP完全陌生。因此,如果需要,请分享一些最佳实践)
class Wps_Wc_Sync {
public function get_wc_products() {
add_action( 'wp_ajax_nopriv_parseCsvAjax', array($this, 'wps_ajax_parseCsvAjax') );
add_action( 'wp_ajax_parseCsvAjax', array($this, 'wps_ajax_parseCsvAjax') );
?>
<script>
jQuery( document ).ready(function($) {
console.log('ajax');
parseCsvAjax(0);
function parseCsvAjax(lastfile = 0) {
$.ajax({
type: "POST",
dataType: 'json',
url: '/wp-admin/admin-ajax.php',
data: {
action: 'parseCsvAjax',
lastfile: lastfile,
},
success: function (data) {
console.log(data);
},
error: function (jqXHT, textStatus, errorThrown) {console.log('Error');}
});
}
});
</script>
<?php
public function wps_ajax_parseCsvAjax($lastfile = 0) {
echo 'testAJAX1';
exit();
return true;
}
}
}发布于 2019-04-30 21:54:56
尝尝这个。未测试
<?php
/*
Plugin Name: Test
Version: 1.0
Plugin URI:
Description: test desc
Author: Vel
Author URI: Test
*/
class Wps_Wc_Sync {
function __construct(){
add_action( 'wp_enqueue_scripts', array($this, 'wpsp_enqueue_scripts_styles') );
add_action('wp_ajax_wpsp_admin_ajax_method', array($this, 'wpsb_fnc_ajax_handler'));
add_action('wp_ajax_nopriv_wpsp_admin_ajax_method', array($this, 'wpsb_fnc_ajax_handler'));
add_action("wp_footer", array($this, "ajax_call_footer"));
}
public function wpsp_enqueue_scripts_styles(){
echo '<script>var wpsp_admin_ajax_url = "'.admin_url("admin-ajax.php").'";</script>';
}
public function wpsb_fnc_ajax_handler(){
$gotomethod = trim($_POST['gotomethod']);
if(!empty($gotomethod) && method_exists($this, $gotomethod)){
$rtnval = call_user_method($gotomethod,$this, $_POST);
die($rtnval);
}else
die('no-method found');
}
public function test(){
print_r($_POST);
exit;
}
public function ajax_call_footer(){
?>
<script>
jQuery( document ).ready(function($) {
console.log('ajax');
parseCsvAjax(0);
function parseCsvAjax(lastfile = 0) {
jQuery.ajax({
type: "POST",
url: wpsp_admin_ajax_url,
data: {
action: 'wpsb_fnc_ajax_handler',
gotomethod:'test',
lastfile: lastfile,
},
success: function (data) {
console.log(data);
},
error: function (jqXHT, textStatus, errorThrown) {console.log('Error');}
});
}
});
</script>
<?php
}
}
$wps_wc_sync = new Wps_Wc_Sync();发布于 2019-05-02 15:22:22
上面的答案不起作用。但真正起作用的是在我的插件init (插件的主文件)中调用这个类。
function run_wps_wc() {
$plugin = new Wps_Wc();
$plugin->run();
$sync = new Wps_Wc_Sync();
}
run_wps_wc();https://stackoverflow.com/questions/55921609
复制相似问题