我有三个文件。我的主要php文件,functions.php,然后是我的js文件。
如何将这个php变量传递给js?这是我的 MAIN PHP FILE
的代码function ccss_show_tag_recipes() {
global $post;
global $wp;
$html = '';
$url = home_url( $wp->request );
$path = parse_url($url, PHP_URL_PATH);
$pathFragments = explode('/', $path);
$currentPage = end($pathFragments); //I WANT TO PASS THIS TO MY JS FILE
$term_tags = get_terms('cp_recipe_tags');
$term_cats = get_terms('cp_recipe_category');
$recipetype = array();
$recipecat = array();
foreach($term_tags as $term) {
$recipetype[] = $term->slug;
}
foreach($term_cats as $term) {
$recipecat[] = $term->slug;
}
if ( in_array( $currentPage , $recipecat ) ) {
$html = ccss_load_phases($html,$currentPage);
}
}
这是css_load_phases()的函数;
function ccss_load_phases($html = '',$currentPage){
//CODE HERE etc
$html .= '<div id="btn-wrapper-'.$termid.'" class="btn-wrapper"><a id="'.$termid.'" class="load-more-btn" href="#">Load more recipes</a></div>';
}
上面的代码是触发Ajax调用,我只能得到按钮ID。
这是AJAX文件代码:
(function($) {
$(document).on( 'click', 'a.load-more-btn', function( event ) {
var a = $(this).attr('id'); // I CAN ONLY GET THE ID SINCE IT WAS TRIGGERED BY BUTTON CLICK, how to include $currentPage?
var button = $(this),
data = {
'action': 'ajax_loadmore',
'termID': a
};
event.preventDefault();
$.ajax({
url: ajaxloadmore.ajaxurl,
data: data,
type: 'post',
beforeSend : function () {
button.text('Loading...'); // change the button text, you can also add a preloader image
},
success: function( result ) {
//console.log(data.post_gallery_imgs);
$('#cooked-recipe-list-'+a+' ').append(result).fadeIn();
c
//alert( result );
},
complete: function() {
button.remove(); // if no data, remove the button as well
//$('body').find('a#'+a+'').remove();
}
})
})
})(jQuery);
如何将$ currentPage php变量传递给我的Ajax / Js文件?所以我可以在这里使用它:
add_action( 'wp_ajax_nopriv_ajax_loadmore', 'my_ajax_loadmore' );
add_action( 'wp_ajax_ajax_loadmore', 'my_ajax_loadmore' );
function my_ajax_loadmore() {
$termID = $_POST['termID']; //ONLY THE BUTTON ID WAS RETRIEVED
}
答案 0 :(得分:1)
在你的函数ccss_load_phases中,包含一个隐藏的输入。
function ccss_load_phases($html = '',$currentPage){
$html .= '<div id="btn-wrapper-'.$termid.'" class="btn-wrapper">
<a id="'.$termid.'" class="load-more-btn" href="#">Load more recipes</a>
<input type="hidden" id="currentPage" value="'.$currentPage.'" />
</div>';
}
现在您应该可以通过引用在您的javascript中访问它:
$('#currentPage').val();
或者是value();
答案 1 :(得分:0)
我通常将变量值写入隐藏的输入类型,然后使用id或名称访问
主要php文件:
echo "<input type='hidden' value='$currentPage' name='currenPage' id='currentPage'>";
.js文件
$("#currentPage").val()