您可以本地化脚本,并将nonce和ajax url传递给脚本
Learn more about script localization.
function wpse_206839() {
// Register our script just like we would enqueue it - for WordPress references
wp_register_script( \'my-special-script\', \'directory/my-special-script.js\', array( \'jquery\' ), false, true );
// Create any data in PHP that we may need to use in our JS file
$local_arr = array(
\'ajaxurl\' => admin_url( \'admin-ajax.php\' ),
\'security\' => wp_create_nonce( \'my-special-string\' )
);
// Assign that data to our script as an JS object
wp_localize_script( \'my-special-script\', \'specialObj\', $local_arr );
// Enqueue our script
wp_enqueue_script( \'my-special-script\' );
}
add_action( \'wp_enqueue_scripts\', \'wpse_206839\' );
这将允许我们访问JS中的nonce as
console.log( specialObj.security );