gpt4 book ai didi

javascript - 如何正确将 php 变量传递给 ajax 调用?

转载 作者:行者123 更新时间:2023-12-03 02:13:34 24 4
gpt4 key购买 nike

我为此准备了三个文件。我的主 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

}

最佳答案

在您的函数 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();

关于javascript - 如何正确将 php 变量传递给 ajax 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49451967/

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