我似乎无法让jquery在插件中调用php处理函数。请帮忙。TQ公司
更新:我更新了代码。它现在正在工作。
我的php文件
// INIT
function nizam_scripts() {
wp_enqueue_script( \'nizam_ajax\', plugin_dir_url( __FILE__ ) . \'/nizam_plugin.js\', array( \'jquery\' ) );
wp_localize_script(\'nizam_ajax\', \'nizam_handler\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );
}
add_action(\'wp_print_scripts\', \'nizam_scripts\');
// SHORTCODE
function nizam_shortcode(){
$html .= \'<input size="10" type="text" class="ajax_bahagian" name="bahagian" value="100">\';
$html .= \'<button class="btn_add" onclick="window.location.href = \\\'javascript:void(0)\\\';">Add</button>\';
return $html;
}
add_shortcode( \'nizam_plugin\', \'nizam_shortcode\' );
// HANDLER
function nizam_handler() {
if ( isset($_REQUEST) ) {
$bahagian = $_REQUEST[\'bahagian\'];
echo $bahagian;
}
// Always die in functions echoing ajax content
wp_die();
}
add_action( \'wp_ajax_nizam_handler\', \'nizam_handler\' );
add_action( \'wp_ajax_nopriv_nizam_handler\', \'nizam_handler\' );
我的jQuery
jQuery(document).ready( function($) {
$(\'.btn_add\').on(\'click\', function(event) {
var bahagian = $(\'.ajax_bahagian\').val();
$.ajax({
url: ajaxurl,
data: {
\'action\' : \'nizam_handler\',
\'bahagian\' : bahagian
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
});