[英]Wordpress AJAX request on admin-ajax.php gives error 400
我正在嘗試創建一個 Wordpress 插件,它將接收一個簡單的 AJAX 請求,並且暫時只發布它的正文。 我的代碼是:
文件 /wp-content/plugins/prova/prova.php:
<?php
/**
* Plugin Name: My Basics Plugin
* Plugin URI: https://example.com/plugins/the-basics/
* Description: Handle the basics with this plugin.
*/
function risposta_mia_azione() {
$param = $_POST["param"];
echo $param;
wp_die();
}
/**
* Register the "book" custom post type
*/
function pluginprefix_setup_post_type() {
}
add_action( 'init', 'pluginprefix_setup_post_type' );
/**
* Activate the plugin.
*/
function pluginprefix_activate() {
}
register_activation_hook( __FILE__, 'pluginprefix_activate' );
/**
* Deactivation hook.
*/
function pluginprefix_deactivate() {
}
register_deactivation_hook( __FILE__, 'pluginprefix_deactivate' );
/**
* Uninstallation hook.
*/
function pluginprefix_uninstall() {
}
register_uninstall_hook( __FILE__, 'pluginprefix_uninstall' );
add_action("wp_ajax_nopriv_mia_azione", "risposta_mia_azione");
?>
我的 Wordpress 安裝的根目錄是http://123.compute.amazonaws.com/wordpress/
。 Now, if I open the dev tools console inside a page of that installation and paste the following jQuery ajax call I will get a POST http://132.compute.amazonaws.com/wordpress/wp-admin/admin-ajax.php 400 (Bad Request)
:
(function( $ ) {
$.ajax({
url : 'http://123.compute.amazonaws.com/wordpress/wp-admin/admin-ajax.php',
data : {"action" : "mia_azione", "param" : "ciao"},
method : 'POST',
success : function( response ){ console.log(response) },
error : function(error){ console.log(error) }
})
})(jQuery)
我已經很多年沒有接觸過 Wordpress 並且我對 Wordpress 的底層非常不熟悉,從我在類似問題中讀到的內容來看,這通常是請求格式不正確時的情況,但我真的看不到我的錯誤。 例如,像這樣的調用:
ajaxresponse = await fetch("http://ec2-3-129-17-101.us-east-2.compute.amazonaws.com/wordpress/wp-admin/admin-ajax.php", {
method: 'POST', mode: 'no-cors',
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({action: "mia_azione", param: "ciao"})
});
會給我這樣的回應:
body: ReadableStream
bodyUsed: true
headers: Headers {}
ok: false
redirected: false
status: 400
statusText: "Bad Request"
type: "basic"
url: "http://123.compute.amazonaws.com/wordpress/w
有人可以幫助我嗎?
編輯:正如響應所指出的,我使用了錯誤的功能-我需要的是: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/
也許你需要這樣的東西:
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.