我想尽一切办法,但还是收到了400 Ajax WordPress的坏请求。我尝试应用在其他线程中找到的序列化和答案,但仍然得到400个错误。
Custom Page Template index.php
add_action( \'wp_enqueue_scripts\', \'myblog_ajax_enqueue\' );
function myblog_ajax_enqueue() {
wp_enqueue_script(\'myblog-ajax-script\', get_stylesheet_directory_uri() . \'/template-parts/templates/blog/js/ajax.js\',array(\'jquery\'));
wp_localize_script( \'myblog-ajax-script\',\'myblog_ajax_obj\', array(\'ajaxurl\' => admin_url( \'admin-ajax.php\' ),\'nonce\' => wp_create_nonce(\'ajax-nonce\')));
}
blogcontent.php
function myblog_ajax_request() {
$nonce = $_POST[\'nonce\'];
if ( ! wp_verify_nonce( $nonce, \'myblog-ajax-script\' ) ) {
die( \'Nonce value cannot be verified.\' );
}
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST[\'fruit\'];
// Let\'s take the data that was sent and do something with it
if ( $fruit == \'Banana\' ) {
$fruit = \'Apple\';
}
echo $fruit;
}
die();
}
add_action( \'wp_ajax_myblog_ajax_request\', \'myblog_ajax_request\' );
add_action( \'wp_ajax_nopriv_myblog_ajax_request\', \'myblog_ajax_request\' );
Ajax.Js
jQuery(document).ready(function($) {
var fruit = \'Banana\';
// This does the ajax request
$.ajax({
url: myblog_ajax_obj.ajaxurl,
data: JSON.stringify({
\'action\': \'myblog_ajax_request\',
\'fruit\': fruit,
\'nonce\': myblog_ajax_obj.nonce
}),
success: function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown) {
console.log(errorThrown);
},
dateType: \'json\',
contentType: \'application/json; charset=utf-8\'
});
});
SO网友:Az Rieil
发送是作为对象,而不是JSON字符串
删除内容类型,您应该让默认值(application/x-www-form-urlencoded
)
删除数据类型-您可以将响应作为文本而不是json发送。(用于JSON响应wp_send_json
)
确保在init文件(插件主文件或functions.php)中注册ajax操作
您还可以尝试在wp admin/admin ajax中一步一步地调试它。php。400错误表示您代码获取此文件,但无法识别操作
url: myblog_ajax_obj.ajaxurl,
data: {
action: \'myblog_ajax_request\',
fruit: fruit,
nonce: myblog_ajax_obj.nonce
},
success: function(data) {
console.log(data);
}