我如何将ajax与wordpress一起使用



我是ajax的新手。 我想在页面上放置一个组合框。组合框包含选项按受欢迎程度、价格和日期。

我想用 ajax 更改div 的内容而不重新加载页面。

例如,我正在展示手表的产品。 当用户更改组合框中的值时,页面上显示的值/图像将相应更改。

1)我想知道如何将Ajax与文字新闻一起使用。2)代码来实现这一点。

我正在使用以下代码:

            <div class="prodimg">

<ul class="rcollpro">
    <?php
        $ordr ='date';
        $args = array( 'post_type' => 'product',  'product_cat' => 'Rings', 'stock' => 1, 'posts_per_page' => 12, 'orderby' =>'$ordr','order' => 'DESC' );
        $loop = new WP_Query( $args );
        while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
                <li class="rcollproli">    
                    <a href="<?php the_permalink(); ?>"><?php if (has_post_thumbnail( $loop->post->ID )) echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog'); else echo '<img src="'.woocommerce_placeholder_img_src().'" alt="Placeholder" width="65px" height="115px" />'; ?></a>
                        <h3><?php the_title(); ?></h3>
                           <span class="price"><?php echo $product->get_price_html(); ?></span><br />

                    <?php woocommerce_template_loop_add_to_cart( $loop->post, $product ); ?>
                </li><!-- /span3 -->
    <?php endwhile; ?>
    <?php wp_reset_query(); ?>
</ul><!-- /row-fluid -->
            </div>

你实际上不需要实现Ajax,但你可以用简单的JS来实现。我可以与您分享一个简单的代码供您参考。

<script type="text/javascript">
 function hourChange(selectObj) {
   var selectIndex=selectObj.selectedIndex;
   var selectValue=selectObj.options[selectIndex].text;
   var output=document.getElementById("output");
   //alert(output.innerText);
   output.innerHTML=selectValue;
 }
</script>
<select id="hour" onchange="hourChange(this);">
  <option>1</option>
  <option>2</option>
</select>
<p/>
you selected: <span id="output">1</span>

在简单的 HTML 文件中尝试此操作。而且在WP中也很容易实现它。

您可以在下面找到适用于您的代码的解决方案:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
$( document ).ready(function() {
$("#selector").change(function() {
   var selectedValue = $("#selector option:selected").val();
   alert('Selected text ' + selectedValue);
});});
</script>
</head>
    <body>
<select name="orderby" class="orderby" id="selector"> 
<option value="menu_order">Default sorting</option> 
<option value="popularity">Sort by popularity</option> 
<option value="date ">Sort by newness</option> 
<option value="price">Sort by price: low to high</option> 
<option value="price-desc">Sort by price: high to low</option> 
</select> 
</body>
</html>

最新更新