ajax - 'Bad request' (400) error with WordPress Ajax
问题描述
I don't understand why I get a 400 'bad request' error with the Ajax code below. I don't get any Apache error btw:
PHP (functions.php)
function load_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_script('main_js', get_stylesheet_directory_uri() . '/dist/scripts/main.js', array('jquery'), true);
wp_localize_script('main_js', 'WPaAjax', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'load_scripts');
function send_message_function() {
echo 'YES!';
exit;
}
add_action('wp_ajax_send_message', 'send_message_function');
add_action('wp_ajax_nopriv_send_message', 'send_message_function');
JS (main.js)
$('.contact_form').submit(function(e) {
e.preventDefault();
var data = $(this).serializeArray();
$.post(WPaAjax.ajaxurl, data, function(response) {
$('body').append(response);
});
});
解决方案
The Bad Request
error message you're seeing is because WordPress considers your request -wait for it- invalid:
You're passing an array of objects to $.post when it expects a plain object or a string. You want to use FormData instead:
$('.contact_form').submit(function(e) { e.preventDefault(); var data = new FormData($(this)[0]); $.post(WPaAjax.ajaxurl, data, function(response) { $('body').append(response); }); });
and:
WordPress expects the
action
parameter to be included with your request, which seems to be missing from your code. So:$('.contact_form').submit(function(e) { e.preventDefault(); var data = new FormData($(this)[0]); data.append("action", "send_message"); $.post(WPaAjax.ajaxurl, data, function(response) { $('body').append(response); }); });
推荐阅读
- email - 如何在gmail收件箱预览中显示图像
- vue.js - 如何在安装生命周期挂钩之前填充数组
- .htaccess - 如何从您的 URL 中删除所有 /page.html
- javascript - d3.js 文本未设置样式
- c# - 获取所有月份和年份中没有任何订单的产品列表
- javascript - 获取不包括其子元素的 div 元素的文本内容
- c++ - 尝试执行 shared_from_this 时,由共享指针引用的类中的类的共享指针会出错
- python - 从 python 中的 azure keyvault 中检索机密列表
- laravel-5 - 如何实现这条路线?
- python - 启动 mu-editor 时有关 PyQt5/QtCore.so 的 ImportError