繁体   English   中英

香草 JS AJAX 在 PHP 中调用 function? WP_query

[英]vanilla JS AJAX call function in PHP ? WP_query

我无法在我的 Function.php 中调用我的 function

  1. 排队脚本和本地化
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' );

  1. Function 在 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
}
  1. 这是我从前端打来的电话,我什至无法让 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 有人可以帮助我并告诉我这有什么问题吗

就像我在评论中所说的那样,后端要求您以正常的 POST 方式发送请求,而不是 JSON。

因此,使用application/x-www-form-urlencoded作为您的 header 并在正文中发送查询字符串,而不是 JSON。

let _data = { action : 'a_product_filter', product_something: 'value that i want to send to the server'};
fetch(a_product_filter.ajax_url, {
    method: 'POST',
    body: (new URLSearchParams(_data)).toString(),
    headers: { 'Content-type': 'application/x-www-form-urlencoded' }
})
.then(response => response.text())
.then(product_html => document.getElementById('container').insertAdjacentHTML(product_html));
// put the markup created by server and put it inside somewhere in the frontend

然后在后端,为该请求做准备。 这是您可以在服务器中使用的未经测试的代码。 这样当前端请求它时,您的服务器(将处理请求的 PHP 代码将给出您想要响应的产品的标记)。

只要遵循这个想法。 创建标记并响应( echoexit )。

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() {
    // $variable = $_POST['product_something'];
    $html_markup = _e('No product matching your criteria.');
    $args = array( 
        'post_type' => 'product', 
        'posts_per_page' => 5, 
        'product_tag' => 'FEMALE' //just for testing without passing a variable
    );
    $loop = new WP_Query($args);
    if ($loop->found_posts > 0) {
        // get template in string
        ob_start();
        wc_get_template_part('content', 'product');
        $template = ob_get_contents();
        ob_end_clean();
        $html_markup = '<ul class="products">';
        foreach ($loop->get_posts() as $post) {
            $html_markup .= '<li>'; // initialize list item    
            $html_markup .= $template; // add the template
            $html_markup .= '<a href="' . get_permalink($post->ID) . '">' . get_title($post->ID). '</a>'; // link and title
            $html_markup .= has_post_thumbnail( $loop->post->ID) ? get_the_post_thumbnail($post->ID, 'shop_catalog'); : '<img src="placeholder.jpg" />' ; // image of product
            $html_markup .= '</li>'; // end list item
        }
        $html_markup .= '</ul>';
    }

    echo $html_markup;
    exit;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM