【发布时间】:2019-06-14 07:36:28
【问题描述】:
所以我在 Ajax 方面的经验有限,我不完全确定如何调试/解决问题。有问题的错误是;
admin-ajax.php - 400 错误请求 (xhr)。
我检查了加载的资源,我可以得到“0”的响应。查看它我可以看到“0”响应意味着未设置操作(在 ajax 数据中)或找不到操作的回调函数。
看到我设置了一个动作,我只能假设这是因为找不到回调函数。但是检查代码没有回调中的拼写错误?
如果我能得到任何帮助,我们将不胜感激。
functions.php
add_action('wp_head', function(){
require_once( get_stylesheet_directory() .'/inc/better-comments.php' );
require( get_stylesheet_directory() .'/inc/ajax.php' );
});
ajax.php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
add_action('wp_ajax_nopriv_front_load_more', 'front_load_more');
add_action('wp_ajax_front_load_more', 'front_load_more');
function front_load_more() {
global $post;
$post = get_post( $_POST['post_id'] );
setup_postdata( $post );
wp_list_comments( array( 'callback' => 'better_comments' ) );
die();
};
theme.js
jQuery(document).ready(function($){
$(document).on('click', '.front-load-more', function(){
var button = $(this);
// decrease the current comment page value
cpage--;
$.ajax({
url : ajaxurl, // AJAX handler, declared before
data : {
'action' : 'front_load_more',
'post_id': parent_post_id, // the current post
'cpage' : cpage, // current comment page
},
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...'); // preloader here
},
success : function( data ){
if( data ) {
$('ol.comment-list').append( data );
button.text('More comments');
// if the last page, remove the button
if ( cpage == 1 )
button.remove();
} else {
button.remove();
}
}
});
return false;
});
});
cmets.php(触发器)
<?php
$cpage = get_query_var('cpage') ? get_query_var('cpage') : 1;
if( $cpage > 1 ) {
echo '<a class="btn btn-block btn-soft-primary transition-3d-hover front-load-more">Load More</a>
<script>
var ajaxurl = \'' . admin_url('admin-ajax.php') . '\',
parent_post_id = ' . get_the_ID() . ',
cpage = ' . $cpage . '
</script>';
}
?>
修正 - add_action('wp_ajax_nopriv_front_load_more', 'front_load_more');
修正 - add_action('wp_ajax_front_load_more', 'front_load_more');
编辑:1 月 21 日 15:23 正如@cabrerahector 所说,我的 ajax.php 文件中有代码需要移动到我的 functions.php 文件中。这解决了错误的请求问题。
【问题讨论】:
-
front-load-more和front_load_more之间存在差异。坚持下划线。另外,您确定要使用 admin-url 吗?该功能是否要求用户是登录管理员? -
我认为css句柄不重要吗?不是这样吗?也没有分配
add_action('wp_ajax_nopriv_front-load-more', 'front-load-more');的功能,所以我认为这会否定这个问题。 -
我注意到你的意思,在 add_action 句柄中。 (花了我一秒钟。)我已经修改了这个,错误仍然没有改变。
-
您在
ajax.php中的代码应该在functions.php中。 -
完成!关于空响应问题,您应该为此打开一个新问题。但是,我在您的代码中注意到显然
parent_post_id尚未在任何地方初始化。