簡體   English   中英

在 Ajax 調用中將 JavaScript 變量傳遞給 PHP 函數?

[英]Pass JavaScript variable to PHP function within Ajax call?

我正在嘗試創建一個 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 調用的數據操作中傳遞變量,但沒有任何效果。 任何想法我怎么能做到這一點?

我假設您的 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 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM