如何在jQuery ajax请求中将多个值作为对象添加到单个参数中

How to add multiple values as an object to a single parameter in a jQuery ajax request?

本文关键字:对象 添加 参数 单个 jQuery ajax 请求      更新时间:2023-09-26

当复选框被选中时,我试图将多个值添加到特定的数据参数'category_values'

category = []
                jQuery('#rpd_filter_categ:checked').map(function() {
                    category.push(jQuery(this).attr('data-value'));
                }); 
category = jQuery('#rpd_filter_categ:checked').attr('data-value');
jQuery.ajax({
        type: 'POST',
        url: ajaxurl,
        // dataType: 'json',
        traditional: true,
        data: {
            'action'            :   'ajax_filter_listings',
            'action_values'     :   action,
            'category_values'   :   category,
            ...
        },
        success: ...
function ajax_filter_listings(){
$categ_array              =   '';
     $allowed_html   =   array();
        if (isset($_POST['category_values']) && trim($_POST['category_values']) != 'All Types' && $_POST['category_values']!=''&& $_POST['category_values']!='all' && $_POST['category_values']!='all-types'){
            $taxcateg_include   =   sanitize_title ( wp_kses(  $_POST['category_values'],$allowed_html  ) );
            $categ_array=array(
                'taxonomy' => 'property_category',
                'field' => 'slug',
                'terms' => $taxcateg_include
            );
        }

它适用于单个选中的选项,但如果选中了两个以上的选项,则会得到:

  • 无结果
  • 只有第一个选项按字母顺序排列
  • 最后选择

当我检查console -> request -> postData时:

  • 在值%2C
  • 之间添加字符
  • 为第二个值创建一个新对象

我越看这个,我就越困惑。有人能给我指个方向吗?

任何帮助都非常感谢!

您的字段似乎都具有相同的id (rpd_filter_categ),但id应该是唯一的,因此最好将其用作类名。

使用这个类,你可以得到这样的类别:

var categories = [];
jQuery('.rpd_filter_categ:checked').each(function() {
  categories.push(jQuery(this).attr('data-value'));
});
jQuery.ajax({
etc...