在过去的几天里,我一直在努力解决同样的问题。
我是Wordpress的新手,所以这可能不是一个百分之百正确的方法。如果有人发现任何错误,我将尝试更正(如果发现任何错误,请发表评论)。
以下是最终对我起作用的代码:
插件的主php文件:
<?php
/*
Plugin Name: My plugin
Description:
Version: 1.0
Author: Pirate
*/
class MyPlugin
{
public function __construct()
{
// Adding an action for both logged and not logged users
add_action(\'wp_ajax_myplugin_action\', array($this, \'myplugin_handle_ajax\'));
add_action(\'wp_ajax_nopriv_myplugin_action\', array($this, \'myplugin_handle_ajax\'));
// Adding action to wp_enqueue_scripts allows you to create nonces in the callback function
add_action(\'wp_enqueue_scripts\', array($this, \'myplugin_load_scripts_styles\'));
}
public function myplugin_load_scripts()
{
wp_enqueue_script(\'myplugin_scripts\', plugins_url(\'myplugin_scripts.js\'), null, \'1.0\', true);
$nonce = wp_create_nonce( \'ajax_validation\' );
wp_localize_script(\'myplugin_scripts\', \'myplugin_data\',
array(
\'url\' => admin_url(\'admin-ajax.php\'),
\'security\' => $nonce,
\'additional_data\' = \'Anything else you need to send to JS\'
)
);
}
public function myplugin_handle_ajax()
{
check_ajax_referer( \'ajax_validation\', \'security\' );
// All the data you sent from JS is in the $_REQUEST
$dataFromJS = $_REQUEST[\'dataFromJS\'];
// Here you can do whatever you want with it - process it, send it to other methods etc.
$dataToSendBack = \'Data I might want to send back to JS\';
wp_send_json_success($dataToSendBack); //parameter is optional
}
//Instantiate the class
$my_plugin = new MyPlugin();
myplugin\\u脚本。js公司
// I did not have to wrap this in $(document).ready(),
// but it might be necessary depending on the execution order of your particular script
$(\'#ajax_button\').on(\'click\', function () {
let ajax_data = {
action: \'myplugin_handle_ajax\',
security: myplugin_data.secuirty,
dataFromJS: \'Whatever I want to send to PHP\'
};
$.ajax({
url: myplugin_data.url,
method: \'POST\',
data: ajax_data,
success: function (response) {
//optional handling of the response
}
})
});