php - 做 ajax 的 WordPress 总是返回 0,但在某些情况下应该返回 1
问题描述
我在 WordPress 中为我的插件创建了一个 AJAX 函数。在插件构造中,我定义了 AJAX 回调:
public function __construct() {
return $this->register();
}
/**
* Register all new files in WooCommerce hooks
*/
public function register() {
if ( is_user_logged_in() ) {
add_action( 'wp_ajax_filter', array( $this, 'filter' ) );
} else {
add_action( 'wp_ajax_nopriv_filter', array( $this, 'filter' ) );
}
}
这是触发 AJAX 调用的 jQuery 函数:
jQuery(document).ready(function () {
jQuery(document).on('click', '.filter-menu li', function () {
var filter_value = jQuery(this).find('.menu-data-inner');
var data = {
'action': 'filter',
'filter': filter_value.attr('data-value'),
'filter_status': 1
};
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
jQuery.post(ajaxurl, data, function () {
jQuery('#content-area').load(location.href + ' #content-area>*', '');
});
}
});
});
在我的请求结束时,我通过 AJAX 刷新了 WordPress 主要内容,并期望我在functions.php
get 中的函数因为DOING_AJAX
.
这是 AJAX 请求调用的函数:
/**
* Filter
*/
public function filter() {
require 'functions/filter.php';
wp_die();
}
这是require的内容:
<?php error_log( $_POST['filter'] ); ?>
所以我的问题是现在我已将此功能添加到我的functions.php
:
add_action( 'init', 'do_something' );
function do_something() {
error_log('INIT');
}
但是我很快就看到这会导致问题,因为在 AJAX 请求上也调用了 init get,但我不希望这样。它应该只在通过按或输入站点 URLINIT
加载页面并按 Enter 时打印。F5
所以我添加了一张支票:
add_action( 'init', 'do_something' );
function do_something() {
if ( ! wp_doing_ajax() ) {
error_log('INIT')
}
}
但是在再次调用 AJAX 之后,调试日志也打印了 INIT 但它不应该。因此,我尝试以这种方式修改在 AJAX 期间调用的函数:
<?php
error_log( $_POST['filter'] );
define( 'DOING_AJAX', true ); ?>
但这也没有成功。error_log
还在。
那么问题是什么?我在这里做错了什么?我的意思是我已经像在 DOCS 中那样做了,但似乎 DOING_AJAX 对我不起作用。
解决方案
你需要
add_action( 'wp_ajax_filter', array( $this, 'filter' ) );
每次您发送 ajax 请求,但这
add_action( 'wp_ajax_nopriv_filter', array( $this, 'filter' ) );
当您需要该用户未登录时,这将更改为:
public function register() {
if ( is_user_logged_in() ) {
add_action( 'wp_ajax_filter', array( $this, 'filter' ) );
} else {
add_action( 'wp_ajax_filter', array( $this, 'filter' ) );
add_action( 'wp_ajax_nopriv_filter', array( $this, 'filter' ) );
}
}
这就是我猜任何请求都会得到 0 的原因
推荐阅读
- sql-server - 如何将逗号分隔的值拆分为其他列
- arrays - 将对象附加到 Powershell 中的数组
- r - 如何制作一个从另一个函数获取值的参数的函数?
- python - 如何在python中添加一个带有dict的特定键项的列表
- python - 是否可以在编辑器中让 VS Code 显示格式化程序规则,就像 linter 一样?
- reactjs - 为什么将 HTML UI 元素作为原子反应原子设计中的原子?
- python - ValueError:形状为 (1,) 的不可广播输出操作数与广播形状 (0,) 不匹配
- git - 如何从下游 Github 分叉中找到最佳更改?
- c - 从文本文件中读取 C 中电话簿代码的信息
- javascript - 我可以单击()一个按钮,但看不到 innerHTML/length。这是怎么回事?(NodeJS)