通过AJAX将参数传递给PHP函数

时间:2016-11-30 15:28:15

标签: php jquery ajax wordpress function

我在WordPress网站上有一个ajax调用,如下所示:

$('.stm-ajax-checkbox-button .button, .stm-ajax-checkbox-instant .stm-option-label input').click(function(e){

        if($(this)[0].className == 'button') {
            e.preventDefault();
        }

        var sold = '';

         if( $('.soldlistings').length ) {
             sold = '(true)';
         }  

        $.ajax({
            url: ajaxurl,
            dataType: 'json',
            context: this,
            data: $(this).closest('form').serialize() + '&action=stm_ajax_filter',
            beforeSend: function () {
                $(this).closest('.stm-accordion-content-wrapper .stm-accordion-inner').addClass('loading');
                $('.stm-ajax-row').addClass('stm-loading');
                $('.classic-filter-row .filter-sidebar .select2-container--default .select2-selection--single .select2-selection__arrow b').addClass('stm-preloader');
            },
            success: function (data) {
                $(this).closest('.stm-accordion-content-wrapper .stm-accordion-inner').removeClass('loading');
                $('.stm-ajax-row').removeClass('stm-loading');
                $('.classic-filter-row .filter-sidebar .select2-container--default .select2-selection--single .select2-selection__arrow b').removeClass('stm-preloader');
                $('.classic-filter-row .filter-sidebar select').prop("disabled", false);

                if(typeof data.html != 'undefined') {
                    $('.stm-ajax-row .stm-isotope-sorting:not(.stm-isotope-sorting-featured-top)').html(data.html);

                    var sortVal = $('.stm-select-sorting select').select2('val');

                    $('.stm-ajax-row').removeClass('stm-loading');
                }

                stm_after_ajax_same_actions(data, sortVal);
            }
        })
    });

然后链接到PHP函数(我不会粘贴整个代码),如下所示:

function stm_ajax_filter() {
}

我想在这个函数中添加一个参数,然后我将用它来帮助解决使用Ajax调用的问题。为此,我在PHP函数中添加了一个参数。如何在Ajax调用中设置此参数?

2 个答案:

答案 0 :(得分:1)

为什么不在AJAX数据属性中添加其他参数?

data: $(this).closest('form').serialize() + '&origin=mainPage&action=stm_ajax_filter',

然后在PHP中你可以只检索'origin'键。

$ajaxOrigin = $_GET["origin"];

// and then pass that variable to your function as an argument
stm_ajax_filter($ajaxOrigin);

答案 1 :(得分:0)

也许在这行数据中:$(this).closest('form')。serialize()+'& action = stm_ajax_filter',

我想你可以试试这个: 数据:$(this).closest('form')。serialize()+'& action = stm_ajax_filter& your_variable ='+ parameter,