0
我有一个ajax表单,根据类别过滤帖子。 设置:发送php值与jQuery ajax函数到php函数
- HTML表单
- PHP函数来呼应输出中
- jQuery的Ajax请求加载PHP 功能
问:我怎样才能解析值PHP函数($测试,见下文)在jQuery的Ajax功能?
表 - 输出HTML选择字段和按钮筛选职位
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<?php
if($terms = get_terms('category', 'orderby=name')) : // to make it simple I use default categories
echo '<select name="categoryfilter"><option>Select category...</option>';
foreach ($terms as $term) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>';
endif;
?>
<button>Apply filter</button>
<input type="hidden" name="action" value="myfilter">
</form>
<div id="response"></div>
PHP函数 - 输出在HTML表单按钮点击
function misha_filter_function($test){
// Do something with $test, but how to parse it with jQuery into this php function?
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'] // ASC или DESC
);
// for taxonomies/categories
if(isset($_POST['categoryfilter']))
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_POST['categoryfilter']
)
);
$query = new WP_Query($args);
if($query->have_posts()) :
while($query->have_posts()): $query->the_post();
echo '<h2>' . $query->post->post_title . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
}
add_action('wp_ajax_myfilter', 'misha_filter_function');
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
jQuery的结果 - 问:如何解析php值$ test到上面的php函数?
jQuery(function($){
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
感谢。你能通过使用/更改我的代码来帮助我多一点吗? – Bob
只需重写代码以使用$ inputValues: '$ inputValues = array(); parse_str($ _ POST ['data'],$ inputValues); 如果(isset($ inputValues ['categoryfilter']))' –
好吧,我怎么发送值的PHP函数与jQuery?那么如何改变它发送数据的jQuery函数呢? – Bob