【发布时间】:2021-05-24 23:24:11
【问题描述】:
我无法在我的 Function.php 中调用我的函数,这就是函数
- 排队脚本和本地化
function my_enqueue() {
wp_enqueue_script( 'wc_shop', get_template_directory_uri() . '/wc_shop.js', array('') );
wp_localize_script( 'wc_shop', 'a_product_filter',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
- function.php 中的函数,我试图调用它来过滤产品
add_action('wp_ajax_a_product_filter', 'a_product_filter');
add_action('wp_ajax_nopriv_a_product_filter', 'a_product_filter');
function a_product_filter() {
echo "called";
$args = array(
'post_type' => 'product',
'posts_per_page' => 5,
'product_tag' => 'FEMALE' //just for testing without passing a variable
);
// Create the new query
$loop = new WP_Query( $args );
// Get products number
$product_count = $loop->post_count;
// If results
if( $product_count > 0 ) :
echo '<ul class="products">';
// Start the loop
while ( $loop->have_posts() ) : $loop->the_post(); //global $product;
//global $post;
wc_get_template_part( 'content', 'product' );
echo '<a href="'.get_permalink($product_id).'">'.get_the_title($product_id).'</a>';
if (has_post_thumbnail( $loop->post->ID ))
echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog');
else
echo '<img src="'.$woocommerce .'/assets/images/placeholder.png" alt="" width="'.$woocommerce->get_image_size('shop_catalog_image_width').'px" height="'.$woocommerce->get_image_size('shop_catalog_image_height').'px" />';
endwhile;
echo '</ul><!--/.products-->';
else :
_e('No product matching your criteria.');
endif; // endif $product_count > 0
}
- 这是我从前端调用的调用,我什至无法让 a_product_filter 回显“调用”
function ajax_call_test(){
// data to be sent to the POST request
let _data = {
action : 'a_product_filter',
}
fetch(a_product_filter.ajax_url , {
method: "POST",
body: JSON.stringify(_data),
headers: {"Content-type": "application/json; charset=UTF-8"}
})
.then(response => response.json())
.then(json => console.log(json));
}
我不断收到 400 Bad Request 有人可以帮助我并告诉我这有什么问题
【问题讨论】:
-
首先,您的 php 返回 HTML,所以您需要
response.text()不response.json()。通过浏览器调用 GET 或使用 Postman 等工具调用 POST,检查您的 php 调用是否返回您期望的结果。 -
我不确定你为什么要向后端发送一个 json 标头,那不应该只是一个普通的 urlencoded 后表单吗?
标签: javascript php ajax wordpress fetch