如何将php变量传递给wordpress AJAX处理程序 [英] How to pass php variable to wordpress AJAX handler
本文介绍了如何将php变量传递给wordpress AJAX处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
努力将一些php变量传递到functions.php中的ajax处理程序函数中
Struggling to pass through some php variables into my ajax handler function in functions.php
下面提供的示例不起作用,可能与挂钩有关,但我找不到有关如何执行此操作的任何信息:
Example provided below doesn't work, probably has something to do with the hooks but I can't find any info on how to do this:
/*Unsubscribe*/
$test_variable = "derp";
function user_unsubscribe($test_variable){
echo json_encode($test_variable);
wp_die();
};
add_action('wp_ajax_user_unsubscribe', 'user_unsubscribe');
add_action('wp_ajax_nopriv_user_unsubscribe', 'user_unsubscribe');
推荐答案
您可以在ajax数据中传递该PHP变量.请检查以下文件,这些文件中我已从jQuery向Ajax函数发送了"test_variable"值.
You can pass that PHP variable in ajax data. Please check below files in which I had send the "test_variable" Value to Ajax Function from jQuery.
jQuery文件代码
Jquery File Code
jQuery(document).ready(function($) {
$('#btn').on('click',function(){
$.ajax({
data: {action: 'get_listing_names','test': global.test_variable},
type: 'post',
url: global.ajax,
success: function(data) {
console.log(data);
}
});
});
});
Functions.php文件代码.
Functions.php file Code.
<?php
/**
* Enqueue scripts and styles.
*
* @since 1.0.0
*/
function ja_global_enqueues() {
wp_enqueue_script(
'global',
get_template_directory_uri() . '/js/global.js',
array( 'jquery' ),
'1.0.0',
true
);
wp_localize_script(
'global',
'global',
array(
'ajax' => admin_url( 'admin-ajax.php' ),
'test_variable' => 'Test Value',
)
);
}
add_action( 'wp_enqueue_scripts', 'ja_global_enqueues' );
add_action('wp_ajax_nopriv_get_listing_names', 'ajax_listings');
add_action('wp_ajax_get_listing_names', 'ajax_listings');
function ajax_listings() {
$test_variable = $_POST['test_variable'];
wp_send_json_success( $test_variable );
}
这篇关于如何将php变量传递给wordpress AJAX处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文