簡體   English   中英

在jQuery中通過Ajax執行PHP文件

[英]Execute PHP file via Ajax in jQuery

當我將這些代碼放置在functions.php中時,它將在購物車圖標旁邊顯示產品編號。 在functions.php中工作正常

但是因為我使用的是緩存插件,所以我無法將代碼包含在functions.php中,或者必須以某種方式從緩存中排除代碼執行。

我認為最好的方法是使用Ajax jQuery。 有沒有更好的辦法??

這是下面我現在放在名為cartbubble.php的文件中的代碼,它是這樣的:

<?
function my_wc_cart_count() 
{
  if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) 
  {     
    $count = WC()->cart->cart_contents_count; ?>
    <a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart'); ?>">
      <?php if ( $count >= 0 ) { ?>
        <span class="cart-contents-count"><?php echo esc_html( $count ); ?></span>
      <?php } ?>
    </a>
    <?php
  }
}

add_action('woo_header_inside', 'my_wc_cart_count');

function my_header_add_to_cart_fragment($fragments) 
{
  ob_start();
  if ($count >= 0) 
  { ?>
    <span class="cart-contents-count"><?php echo WC()->cart->cart_contents_count(); ?></span>
    <?php 
  } ?>

  <?php
    $fragments['span.cart-contents-count'] = ob_get_clean();
    return $fragments;
}

add_filter('woocommerce_add_to_cart_fragments', 'my_header_add_to_cart_fragment');

這是我在header.php中通過ajax jquery調用它的方法:

<script type="text/javascript">
  jQuery(document).ready(function() {
    jQuery.ajax({
      url: '/wp-content/themes/canvas-child/cartbubble.php',
      type: 'POST',
      success: function(result) {
        console.log(result);.
      },
      error: function() {
        console.log('error');
      }
    });
  });
</script>

為什么不執行功能與在functions.php中相同?

提前致謝

您的主要問題是您的方法。 cartbubble.php文件未首先加載WordPress,因此您正在調用的功能不可用。 在WordPress前端和后端的所有正常加載中都會調用functions.php文件,因此您可以在其中使用全部功能。

您仍然可以按照以下方式在functions.php文件中使用AJAX。 WordPress中有一些針對AJAX的特殊操作,可讓您更輕松地使用它。

首先,您需要像這樣將功能附加到您的AJAX掛鈎...

// This will hook into both logged in and anonymous visitors
add_action( 'wp_ajax_my_header_cart_count', 'my_header_cart_count' );
add_action( 'wp_ajax_nopriv_my_header_cart_count', 'my_header_cart_count' );

function my_header_cart_count()
{
    echo WC()->cart->cart_contents_count();
    wp_die();
}

您還應該使用代碼將JS注入頁腳...

add_action( 'wp_footer', 'my_header_cart_javascript' );

function my_header_cart_javascript() { ?>
    <script type="text/javascript" >
    jQuery(document).ready(function($) {

        var data = {
            'action': 'my_header_cart_count'
        };

        jQuery.post(ajaxurl, data, function(response) {
            // Inject the response into the containing span
            $('.cart-contents-count').html(response);
        });
    });
    </script> <?php
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM