[英]Wordpress Admin Ajax 400 (Bad Request)
I have used Wordpress Admin Ajax and the console shows that 400 (Bad Request)我使用过 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);
}
});
});
The Wordpress AJAX process has some basic points that should be followed if you want it to work correctly: Wordpress AJAX 过程有一些基本要点,如果您希望它正常工作,应遵循这些要点:
1.In functions.php add the action you'd like to call from the frontend: 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.Register the localization object in functions.php 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.Create the AJAX request on the frontend 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 );
}
first you shouldn't write the url by yourself.首先你不应该自己写网址。 You could use the localize function to add the url to your javascript file:您可以使用 localize 函数将 url 添加到您的 javascript 文件中:
wp_enqueue_script('myHandle','pathToJS');
wp_localize_script(
'myHandle',
'ajax_obj',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
);
After this you can use ajax_obj.ajax_url
within your script to receive the url.在此之后,您可以在脚本中使用ajax_obj.ajax_url
来接收 url。
Second, did you implement the correct hook?其次,你是否实现了正确的钩子?
// 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' );
Best Regards此致
All Wordpress Ajax call must have action
param which points to hook wp_ajax_{action_param}
or wp_ajax_nopriv_{action_param}
and from there you jump to function from that hooks.所有 Wordpress Ajax 调用都必须具有指向钩子wp_ajax_{action_param}
或wp_ajax_nopriv_{action_param}
action
参数,然后您从该钩子跳转到函数。
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
function my_action() {
$status = $_POST['status'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.