【问题标题】:Pass JavaScript variable to PHP function within Ajax call?在 Ajax 调用中将 JavaScript 变量传递给 PHP 函数?
【发布时间】: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


【解决方案1】:

我认为您的 ajax URL 很好并且可以加载到网站中。 现在你必须修改你的 JS 脚本并且需要在 PHP 部分添加钩子。首先在您的 JS 脚本中修改 data: 行如下:

data: { action : 'get_records_ajax', query: query },

您还可以根据需要添加安全检查。但现在就离开吧。

其次,在您的 PHP 文件中添加以下代码..

add_action( "wp_ajax_nopriv_get_records_ajax", 'get_records_ajax' );
add_action( "wp_ajax_get_records_ajax",        'get_records_ajax' );

然后在您的get_records_ajax 中接收query

function get_records_ajax(){
  $query = sanitize_text_field($_POST['query']);

  //then your rest code


}

它将返回所有帖子。现在你需要在成功块中调整你的 JS 代码:

success: function( response ) {
   console.log(response)
  //adjust here with your HTML dom elements 
}

【讨论】:

    猜你喜欢
    • 2015-12-16
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 2020-09-27
    • 2023-04-03
    • 2013-03-05
    • 1970-01-01
    • 2019-04-21
    相关资源
    最近更新 更多