我正在使用Wordpress Codex中的Ajax参考,并将他们的示例用于管理员端插件
我的插件代码在Woocommerce产品索引页面中创建了一个新的下拉列表,如下所示:
$dmo_select = '<select onchange="dmo_service_update()">';
foreach ($dmo_service_enhancements as $enhancement) {
$dmo_select .= '<option value="'.$enhancement.'">'.$enhancement.'</option>';
}
$dmo_select .= '</select>';
使用Wordpress Codex示例,我可以在更改选择时启动警报对话框:
PHP:
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
wp_enqueue_script('wtd-dmo-update', plugins_url( 'ajax-js.js', __FILE__ ), array('jquery') );
wp_localize_script (
'wtd-dmo-update',
'ajax_object',
array('ajax_url' => admin_url('admin-ajax.php'), 'we_value_3' => 1234 )
);
}
add_action( 'wp_ajax_dmo_service_update_php_2', 'dmo_service_update_php_1' );
function dmo_service_update_php_1() {
global $wpdb;
$whatever = intval( $_POST['whatever_4'] );
$whatever += 10;
echo $whatever;
die();
}
使用Javascript:
function dmo_service_update(){
var data = {
'action': 'dmo_service_update_php_2',
'whatever_4': ajax_object.we_value_3,
};
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert('Got this from the server: ' + response);
});
}
问题是ajax(&#39; 1234&#39;)处理的值在wp_localize_script()函数调用中提供的示例中是硬编码的,这似乎设置了一切。
我需要的是所选选择框的值。我如何将其传递给Ajax,而不是硬编码的值?
最终,我的目标是使用dmo_service_update_php_1 php函数将选择值写入db。任何指针都会非常感激。
答案 0 :(得分:0)
更改select
代码onchange()
触发器以包含this.value
:
<select onchange="dmo_service_update(this.value)">
将值接受到javascript函数
function dmo_service_update(dmo_selected){
var data = {
'action': 'dmo_service_update_php_2',
'dmo_selected' : dmo_selected
};
PHP现在可以将值读取为$ _POST参数:
function dmo_service_update_php_1() {
$selected = $_POST['dmo_selected'];
die();
}