我是Ajax的新手。在ajax函数中,我无法显示变量$competition_id
内容。我使用的是以下代码,但它只显示了ID。
function custom_fixture_template(){
$competition_id = $_POST[ 'competion' ];
echo $competition_id;
$args = array(
'post_type' => array( 'football_fixture' ), // profile and letter are CPTs
'posts_per_page'=>5,
'meta_key' => 'pb_match_date',
'orderby' => 'meta_value',
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'competition',
'field' => 'id',
'terms' => $competition_id
),
),
'meta_query' => array(
array(
'key' => 'pb_match_status',
'value' => 'fixture'
),
)
);
$my_query = null;
$my_query = new WP_Query($args); ?>
}
add_action("wp_ajax_my_custom_fixture_template", "custom_fixture_template");
add_action("wp_ajax_norpiv_my_custom_fixture_template", "custom_fixture_template");
Ajax代码:
jQuery(".fixture-competition").change(
function(){
jQuery.ajax({
url:"<?php echo admin_url();?>admin-ajax.php",
type:"post",
data:{"action":"my_custom_fixture_template",competion:jQuery(this).val()},
success:function(res){
jQuery('.competition-container').remove();
jQuery('.new-fixture').html('');
jQuery('.new-fixture').append(res);
}
});
});
HTML代码:
<select name="fixture-competition" class="fixture-competition">
<?php
$args = array(
'type' => 'football_fixture',
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'competition',
'pad_counts' => false );
$competition_fixture = get_categories($args); ?>
<option value="Select All">--Select--</option>
<?php
foreach ($competition_fixture as $competition) { ?>
<option value="<?php echo $competition->term_id; ?>">
<?php $url = get_term_link($competition);?>
<a href="<?php echo $url;?>"><?php echo $competition->name; ?></a>
</option>
<?php
}
?>
</select>
答案 0 :(得分:0)
你的php函数没有返回任何内容。所以jQuery脚本没有任何东西可以附加到.new-fixture。
您可以执行类似
的操作$my_query = new WP_Query($args); // be carefull of typo (a php closing tag)
echo json_encode($my_query);
然后在ajax响应中,您将能够解析json响应。
success:function(res){
var json = $.parseJSON(res);
console.log(json);
...
}
希望它能给你一些提示......
答案 1 :(得分:0)
我自己用以下代码解决了这个问题:
<div class="team-league-name-top">
<?php
$competition_name = get_term( $competition_id, 'competition' );
echo $competition_name->name;
?>
</div>