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