400 错误请求与 Wordpress AJAX 调用 [英] 400 Bad Request with Wordpress AJAX call
本文介绍了400 错误请求与 Wordpress AJAX 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为 Wordpress 网站的前端开发一个搜索插件.目前我不断收到 400 Bad Request 错误,我不明白为什么.我已经查看了很多关于 SO 和 WordpressStackExchange 的问题,但看不出我哪里出错了,似乎没有什么不合适的.请给我指导:
I'm working on a search plugin for the front-end of a Wordpress site. At the moment I keep getting a 400 Bad Request Error and I can't understand why. I've reviewed many questions on SO and the WordpressStackExchange but cannot see where I'm going wrong, nothing appears to be out of place. Please give me guidance:
plugin.php:
plugin.php:
function my_admin_scripts() {
$localize = array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
);
wp_register_script('veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', '', '', true);
wp_localize_script( 'veh-app-search', 'veh_app_script', $localize);
wp_enqueue_script( 'veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', array( 'jquery' ) );
}
add_action( 'wp_enqueue_scripts', 'my_admin_scripts' );
add_action( 'wp_ajax_the_ajax_hook', 'handle_request' );
add_action( 'wp_ajax_nopriv_the_ajax_hook', 'handle_request' );
//takes care of the $_POST data
function handle_request(){
echo "hello";
}
ajax.js
var data = {
action: 'handle_request',
RequestType: 'category',
Category: jQuery('#Category option:selected').val()
};
jQuery.post(
veh_app_script.ajaxurl,
data,
function(categories){
console.log(categories);
}
);
人们希望在控制台中看到Hello",但我只在控制台中看到错误:
One would expect to see "Hello" in the console but I only see the error in the console:
jquery.js?ver=1.12.4:4 POST http://localhost/wp-admin/admin-ajax.php 400 (Bad Request)
推荐答案
请替换代码并检查
plugin.php
function my_admin_scripts() {
$localize = array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
);
wp_enqueue_script( 'veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', array( 'jquery' ) );
wp_localize_script( 'veh-app-search', 'veh_app_script', $localize);
}
add_action( 'wp_enqueue_scripts', 'my_admin_scripts' );
add_action( 'wp_ajax_handle_request', 'handle_request' );
add_action( 'wp_ajax_nopriv_handle_request', 'handle_request' );
//takes care of the $_POST data
function handle_request(){
echo "hello";
}
ajax.js
var data = {
action: 'handle_request',
RequestType: 'category',
Category: jQuery('#Category option:selected').val()
};
jQuery.post(
veh_app_script.ajaxurl,
data,
function(categories){
console.log(categories);
}
);
这篇关于400 错误请求与 Wordpress AJAX 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文