【发布时间】:2021-02-19 11:27:21
【问题描述】:
我正在尝试创建一个 ajax 搜索表单,如果在帖子标题中找到搜索词,则该表单可以获取 WordPress 帖子。这是我的 PHP 函数:
function get_records_ajax($query) {
$args = array(
'post_type' => array('record'),
'post_status' => array('publish'),
'posts_per_page' => 999,
'nopaging' => true,
'meta_query' => array(
'key' => 'title',
'value' => $query,
'compare' => 'IN',
)
);
$ajaxposts = get_posts( $args );
echo json_encode( $ajaxposts );
exit;
}
这是我的 jQuery 函数:
jQuery('.rrm_search_form').on('submit', function(e){
e.preventDefault();
let query = jQuery(this).find('.rrm_search_input').val();
console.log('search submitted for ' + query);
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php');?>',
dataType: "json",
data: { action : `get_records_ajax(${query})` },
success: function( response ) {
jQuery.each( response, function( key, value ) {
console.log( key, value );
});
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
}
});
});
我尝试了很多不同的语法来尝试在我的 ajax 调用的数据操作中传递变量,但没有任何效果。有什么想法我可以做到这一点吗?
【问题讨论】:
-
您注册回拨到
wp_ajax_*了吗? -
是的,我已经注册了它,如果你不尝试传递变量,即
data: { action : 'get_records_ajax' },它确实有效,尽管它只是返回所有帖子
标签: javascript php jquery ajax wordpress