我通过获取按钮值而遇到问题。 我需要点击Button值来排序php中的一些数据。
如果我尝试一些examples,一切正常。
我不知道如何从点击的按钮中获取值... 我需要这个来排序数组。有人能告诉我如何通过ajax获得点击按钮的价值吗? 谢谢你的想法..
这是我的jQuery:
jQuery(document).ready(function($) {
$("#button1").click(function () {
var data = {
action: 'table_contest',
security : MyAjax.security,
sort: 1
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(MyAjax.ajaxurl, data, function(response) {
//test
alert('Got this from the server: ' + response);
});
});
});
在php中:
// Add the JS
function theme_name_scripts()
{
wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom.js', array('jquery'), '1.0.0', true);
wp_localize_script('custom-script', 'MyAjax', array(
// URL to wp-admin/admin-ajax.php to process the request
'ajaxurl' => admin_url('admin-ajax.php'),
// generate a nonce with a unique ID "myajax-post-comment-nonce"
// so that you can check it later when an AJAX request is sent
'security' => wp_create_nonce('test')
));
}
add_action('wp_enqueue_scripts', 'theme_name_scripts');
function table_contest_function($atts){
check_ajax_referer('test', 'security');
//get how to sort the tabledata
$sort = intval($_POST['sort']);
$atts = shortcode_atts(
array(
'table-id' => ''
), $atts );
// get table data from Plugin TablePress
$table = TablePress::$model_table->load( $atts['table-id'], true, true );
//only get the important data
$data = $table['data'];
//if button was clicked sort asc
if ($sort == '1'){
//sort
asort($data);
}
$output = ......;
echo $output;
}
add_action('wp_ajax_table_contest', 'table_contest_function');
答案 0 :(得分:3)
您只需要使用this关键字获取被点击的元素,这将获得当前范围。
查看以下代码。
jQuery(document).ready(function($) {
$("#button1").click(function () {
var btn_val = $(this).val();
var data = {
action: 'table_contest',
security : MyAjax.security,
sort: 1,
btn : btn_val
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(MyAjax.ajaxurl, data, function(response) {
//test
alert('Got this from the server: ' + response);
});
});
});