我一直在寻找解决方案的几天,但是与使用AJAX的400错误请求相关的所有线程似乎都与我的问题无关,或者也许我只是想念它。
我制作了一个页面,其中列出了主类别的子类别。这部分效果很好。当用户单击类别时,我需要使用AJAX检索与该用户刚刚单击的类别相关的所有产品。
page_template.php
<script type="text/javascript">
jQuery(function($) {
$('.seamBuilder_trigger').click(function() {
var catID = $(this).attr('id');
console.log(catID);
$.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php');?>',
dataType: "html", // add data type
data: {
action : 'get_products'
},
success: function(response) {
console.log(response);
$('.posts-area').html(response);
}
});
return false;
});
});
</script>
<section id="content" class="site-content">
<div id="seam-builder-wrap" class="container">
<?php
$masterCat = 39; // Master category 'Seam Builder' ID is 39)
$taxonomyName = "product_cat";
$termchildren = get_term_children($masterCat, $taxonomyName);
foreach ($termchildren as $child) {
$subCat = get_term_by('id', $child, $taxonomyName); //assigns $subCat to the current subcategory in the loop
$subCat_title = $subCat->name; //gets the name of the subcategory
$cat_id = $subCat->term_id; //gets the ID of the subcategory on its own
$thumbnail_id = get_term_meta($child, 'thumbnail_id', true); //gets the thumbnail of the subcategory
$image = wp_get_attachment_url($thumbnail_id); //gets the URL of the thumbnail
?>
<a id="<?php echo $cat_id ?>" class="seamBuilder_trigger" href="#">
<img src="<?php echo $image ?>" />
<span><?php echo $subCat_title ?></span>
</a>
<?php } //ends for foreach loop above ?>
</div>
<div class="posts-area">
</div>
</section>
functions.php
<?php
function get_products() {
$cat_id = (isset($_POST['cat'])) ? $_POST['cat'] : '';
echo 'hello there' . $cat_id;
// Query Arguments
$args = array(
'cat' => $cat_id,
'post_type' => array('products'),
'post_status' => array('publish'),
'posts_per_page' => -1,
);
// The Query
$ajaxposts = new WP_Query($args);
$output = '';
if ($ajaxposts -> have_posts()) : while ($ajaxposts -> have_posts()) : $ajaxposts -> the_post();
$output .= 'div class="seamBuilderRow">';
$output .= $cat_id;
$output .= '</div>';
endwhile;
endif;
wp_reset_postdata();
wp_die();
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_products');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_products');
?>
我单击应该触发AJAX的类别之一,就收到400错误的请求。有任何想法吗?
您的动作挂钩处理程序是wp_ajax_ get_ajax_posts(和wp_ajax_nopriv_ get_ajax_posts),因此action
参数也应该是get_ajax_posts
。由于不是,WordPress会以400错误请求状态响应您的AJAX呼叫。
这应该工作:
$.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php');?>',
dataType: "html", // add data type
data: {
action : 'get_ajax_posts'
},
success: function(response) {
console.log(response);
$('.posts-area').html(response);
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句