我的jquery ajax不能在我的WordPress网站上工作
问题描述:
<div class="home-thumbs bottom-thumbs">
<?php $home_query_bottom = new WP_Query("cat=&showposts=20&offset=5"); $b = 0; ?>
<ul class="thumbs">
<?php while ($home_query_bottom->have_posts()) : $home_query_bottom->the_post();
$do_not_duplicate = $post->ID; $b++; ?>
<li class="post-<?php the_ID(); ?> thumb"><?php get_the_image(array('custom_key' => array('thumbnail'), 'default_size' => 'thumbnail', 'width' => '160', 'height' => '160')); ?></li>
<?php endwhile; wp_reset_query(); $b = 0; ?>
</ul>
</div>
<div id="output"></div>
<script type="text/javascript">
$('.go-right').click(function(){
$.ajax({
type: "POST",
url: "process_thumbs.php",
data: "showposts=25",
success: function(html){
$("#output").html(html);
}
});
});
</script>
// process_thumbs.php
<body>
<?php $numposts = $_POST['showposts']; ?>
<div><?php echo "this is the amount of posts to be shown: $numposts"; ?></div>
</body>
看起来像一个简单的ajax调用。 .go-right确实存在,它只是在另一个文件中,我测试了点击正在执行。这个Ajax调用基本上不起作用。也许有人可以确定我的代码是否错误。我的jquery ajax不能在我的WordPress网站上工作
理想我想采取WP-查询循环和使用Ajax与不同showposts再次运行该循环,如果有人点击偏移。
答
确保.go-right
是以前 jQuery的代码或(更好的)包装您的jQuery在
$(document).ready(function() {
})
或相似,以确保处理程序是真正连接到您的.go-right
元素
不要在您的process_thumbs.php
中输出<body>
标签,也许这会让jQuery产生混淆。
检查Firebug的控制台/净标签,以确保该请求被真正被发送。
添加一个error
回调到您的.ajax
,以确保您的ajax调用真正得到执行。
呀,使用绝对路径,但有一个WordPress的辅助函数:
...
url: '<?php echo get_bloginfo('url').'/wp-content/myplugin/mycallback';?>'
...
这样一来,所有的网址将是相对于WordPress的根URL。
答
在WordPress的(我使用的版本3.0及以上),由于与其他JavaScript库冲突(即原型),你必须写:的
$JQuery('.go-right').click(function(){
代替
$('.go-right').click(function(){
而且,请检查Firebug以确保链接到您的Jquery库是正确的。
一件事... WordPress的已经包括了jQuery,您可以通过书面形式得到它:
<?php wp_enqueue_script("jquery"); ?>
<?php wp_head(); ?>
第一行必须在第二行之前去(wp_head()),否则将无法正常工作。
答
我重写你的代码文档准备好处理程序中:
$(函数(){ 您的代码 });
它的工作好。
所以还是这是你的代码的位置相关的问题,或者你mispell东西。
跟随我的测试代码:
<html>
<head>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
$.ajax({
type: "POST",
url: "process_thumbs.html",
data: "showposts=25",
success: function(html){
$("#output").html(html);
}
});
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>
感谢。我检查了chrome的开发人员工具,它说我的process_thumbs.php 404错误。说www.url.com/process_thumbs.php,这不是网址。我想在wordpress中你需要绝对路径? – Adam 2011-01-09 17:36:11