如何使用Ajax onclick加载Wordpress Post

时间:2013-03-14 05:58:56

标签: jquery ajax wordpress loops post

我花了几个小时阅读和尝试教程。我似乎无法找到一个有效的解决方案,我知道它应该很容易,但我很难与AJAX。 :(

我想从div中的链接加载Post内容。 以下是我所拥有的。有人可以帮我解决JavaScript方面的问题吗?谢谢!

<ul>
    <?php query_posts('post_type=artwork&posts_per_page=-1'); ?>
    <?php if(have_posts()) : while(have_posts()) : the_post(); ?>
    <li class="mytab">
      <span>
         <h3><?php the_title(); ?></h3>
         <a href="#"><?php the_post_thumbnail('Project'); ?></a>
      </span>
    </li>
    <?php endwhile; endif; wp_reset_query(); ?>
</ul>

<div id="loadAjaxHere"></div>

我想在div #loadAjaxHere

中加载此代码
<div class="myArtwork">
   <h2><?php the_title(); ?></h2>
   <div class="text"><?php the_content(); ?></div>
</div>

感谢您的帮助!!

3 个答案:

答案 0 :(得分:10)

确定, 经过长时间的反复试验,我想我已经解决了这个问题。

这似乎有效,但如果不是这样做的正确方法,请告诉我

使用Javascript:

jQuery.noConflict();
jQuery(document).ready(function($){
    $.ajaxSetup({cache:false});
    $("a.ajax").click(function(){
        var post_url = $(this).attr("href");
        var post_id = $(this).attr("rel");
        $("#tabs").html('<div class="loading">loading...</div>');
    $("#tabs").load(post_url);
    return false;
    });
});

我要显示帖子内容的页面(我使用的是名为“艺术品”的自定义帖子类型:

<ul class="container">
  <?php query_posts('post_type=artwork&posts_per_page=-1'); ?>
  <?php if(have_posts()) : while(have_posts()) : the_post(); ?>
  <li class="mytab">
    <h3><?php the_title(); ?></h3>
    <a href="<?php the_permalink(); ?>" rel="<?php the_ID(); ?>" class="ajax"><?php the_post_thumbnail('Project'); ?></a>
  </li>
  <?php endwhile; endif; wp_reset_query(); ?>
</ul>

<!-- LOAD SINGLE POST CONTENT IN #TABS -->
<div id="tabs"></div>

单个帖子“single-artwork.php”。注意:不要使用get_header或get_footer等:

<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
  <div class="tabcontent" id="tab-<?php the_ID(); ?>">
    <?php the_content(); ?>
  </div>
<?php endwhile; endif; ?>

谢谢!

答案 1 :(得分:3)

添加,如果您只想加载单个帖子的一部分,可以修改

$("#tabs").load(post_url);

$("#tabs").load(post_url + ".tabcontent" );

只会加载div.tabcontent中的所有内容

答案 2 :(得分:3)

Barry的答案是正确的,因为能够通过在URL的末尾添加css选择器表达式来加载部分页面。但是,url和选择器之间需要有一个空格,如下所示:

$("#tabs").load(post_url + " .tabcontent" );

否则传递给.load()的字符串将为http://example.com.tabscontent。但它应该是http://example.com .tabscontent

此外,明智的一句话,使用此方法将阻止jQuery加载和执行<script>标记内的任何代码。但是,仅使用没有选择器的.load(post_url);会成功加载并执行<script>代码中的代码。

详细了解here