嗨,这是我的 WordPress 插件代码
function my_action_callback() {
check_ajax_referer( 'my-special-string', 'security' );
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die();
}
add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_shortcode('my_products','my_shortcode');
function my_shortcode($atts)
{
extract(shortcode_atts(array(
'id'=>''
), $atts));
ob_start();
wp_enqueue_script( 'my-script', plugins_url( 'myplugin/js/example.js' ), array('jquery'), NULL, true);
wp_localize_script( 'script-name', 'MyAjax', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'security' => wp_create_nonce( 'my-special-string' )
));
}
example.js代码
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
security : MyAjax.security,
whatever: 1234
};
$.post(MyAjax.ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
它不会提醒任何值。为什么? 我的短代码[my_products]
最佳答案
在将脚本排入队列之前,您需要先对其进行本地化,而且您当前正在对 my-script
进行入队时本地化 script-name
。
试试这个:
function my_shortcode($atts)
{
extract(shortcode_atts(array(
'id'=>''
), $atts));
ob_start();
// Register the script first.
wp_register_script( 'script-name', plugins_url( 'myplugin/js/example.js' ), array('jquery'), NULL, true);
// Now localize it.
wp_localize_script( 'script-name', 'MyAjax', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'security' => wp_create_nonce( 'my-special-string' )
));
// Now enqueue the script
wp_enqueue_script( 'script-name')
}
关于javascript - Ajax 无法在 WordPress 插件短代码的前端工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24691676/