我使用了Wordpress Admin Ajax,控制台显示400(错误请求)
jQuery('#submitid').click(function(e){
e.preventDefault();
//var newCustomerForm = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "wp-admin/admin-ajax.php",
data: {status: 'status', name: 'name'},
success:function(data){
jQuery("#result").html(data);
}
});
});
答案 0 :(得分:1)
首先,您不应该自己写网址。您可以使用localize函数将网址添加到您的javascript文件中:
wp_enqueue_script('myHandle','pathToJS');
wp_localize_script(
'myHandle',
'ajax_obj',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
);
此后,您可以在脚本中使用ajax_obj.ajax_url
来接收URL。
第二,您实现了正确的钩子吗?
// Only accessible by logged in users
add_action( 'wp_ajax_my_action', 'my_action_callback' );
// Accessible by all visitors
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
最好的问候
答案 1 :(得分:1)
所有Wordpress Ajax调用必须具有action
参数,该参数指向钩子wp_ajax_{action_param}
或wp_ajax_nopriv_{action_param}
,然后从那里跳转到该钩子。
来自Codex:
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
function my_action() {
$status = $_POST['status'];
}
答案 2 :(得分:1)
如果您希望Wordpress AJAX正常运行,它应遵循一些基本要点:
1。在functions.php中,添加您要从前端调用的操作:
function logged_in_action_name() {
// your action if user is logged in
}
function not_logged_in_action_name() {
// your action if user is NOT logged in
}
add_action( 'wp_ajax_logged_in_action_name', 'logged_in_action_name' );
add_action( 'wp_ajax_nopriv_not_logged_in_action_name', 'not_logged_in_action_name' );
2。在functions.php中注册本地化对象
// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Localize the script with new data
$some_object = array(
'ajax_url' => admin_url( 'admin-ajax.php' )
);
wp_localize_script( 'some_handle', 'ajax_object', $some_object );
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
3。在前端创建AJAX请求
// source: https://codex.wordpress.org/AJAX_in_Plugins
var data = {
'action': 'not_logged_in_action_name',
'whatever': 1234
};
jQuery.post( ajax_object.ajax_url, data, function( response ) {
console.log( response );
}