gpt4 book ai didi

php - 如何获取点击ajax时的按钮值

转载 作者:行者123 更新时间:2023-12-01 07:42:10 24 4
gpt4 key购买 nike

我在获取按钮值时遇到问题。我需要在单击时获取按钮值以对 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');

最佳答案

您只需使用 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);
});
});
});

关于php - 如何获取点击ajax时的按钮值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45832029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com