【问题标题】:vanilla JS AJAX call function in PHP ? WP_queryPHP中的香草JS AJAX调用函数? WP_query
【发布时间】:2021-05-24 23:24:11
【问题描述】:

我无法在我的 Function.php 中调用我的函数,这就是函数

  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.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 有人可以帮助我并告诉我这有什么问题

【问题讨论】:

  • 首先,您的 php 返回 HTML,所以您需要 response.text() response.json()。通过浏览器调用 GET 或使用 Postman 等工具调用 POST,检查您的 php 调用是否返回您期望的结果。
  • 我不确定你为什么要向后端发送一个 json 标头,那不应该只是一个普通的 urlencoded 后表单吗?

标签: javascript php ajax wordpress fetch


【解决方案1】:

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

所以使用application/x-www-form-urlencoded 作为标题并在正文中发送查询字符串,而不是 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;
}

【讨论】:

  • 旁注:使用 ajax nonce 作为附加检查
  • thxx 我通过将正文包装在new URLSearchParams() 和标题到headers: {"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"} 来修复它,正如您在回答中提到的并解决了它最初我的Jquery ajax 调用正在工作并且认为正文在request 只是不知道如何将 Fetchs 正文更改为 Object 会为您投票,但我不能导致新帐户限制
  • @Ojisan 肯定不会很高兴这有帮助
猜你喜欢
  • 2023-03-20
  • 2020-10-20
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 2019-01-18
  • 2018-11-19
相关资源
最近更新 更多