2013-03-14 55 views
6

我花了数小时阅读和试用教程。我似乎找不到解决方案,我知道它应该很容易,但我与AJAX斗争。 :(如何使用Ajax加载Wordpress帖子onclick

我要发布的内容从一个div链路负载。 下面是我。有人可以帮我与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> 

我希望加载这个在格码#loadAjaxHere

<div class="myArtwork"> 
    <h2><?php the_title(); ?></h2> 
    <div class="text"><?php the_content(); ?></div> 
</div> 

谢谢你的帮助!

+0

你用什么来定义你想要检索哪个帖子?什么是附加了点击功能的元素?你熟悉functions.php文件吗? – Ohgodwhy 2013-03-14 06:10:57

+0

您必须在JavaScript端包含wp-blog-header.php。 – 2013-03-14 07:40:26

+0

Try: $ folder = substr(substr($ _ SERVER [“REQUEST_URI”],1),0,strpos(substr($ _ SERVER [“REQUEST_URI”],1),“/”)); $ ajax_url = realpath($ _ SERVER [“DOCUMENT_ROOT”])。'/'。$ folder。'/ wp-blog-header.php'; require($ ajax_url); 位于您的外部ajax请求页面的顶部。 – 2013-03-14 07:46:07

回答

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> 

和单后“单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; ?> 

谢谢!

3

我想补充,如果你只是想在一个职位的一部分来加载,你可以ammend

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

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

这将在一切只加载在div.tabcontent

+0

在逗号和点之间使用空格... $(“#tabs”)。load(post_url +'.tabcontent'); – 2017-01-23 18:02:00

3

Barry的答案对于能够通过在URL末尾添加css选择器表达式来加载部分页面是正确的。然而,将需要的URL和选择之间的空间,像这样:

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

否则传递给​​字符串是http://example.com.tabscontent。但它应该是http://example.com .tabscontent

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

阅读更多关于here