[英]AJAX: 400 bad request
我一直在寻找几天的解决方案,但是与使用 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>
功能。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 Bad Request 状态响应您的 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);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.