代码之家  ›  专栏  ›  技术社区  ›  Reece

WordPress Ajax多数据参数

  •  0
  • Reece  · 技术社区  · 6 年前

    所以我在我的文章上创建了可过滤性,这样我就可以按价格、属性类型等对它们进行过滤。但现在我也有任务做它,这样只有八个属性将显示,直到点击一个加载更多按钮,然后八个更多将加载。我环顾四周,可以看到我需要在wp_查询中使用offset,然后在js中增加显示的文章数。但我的问题是我在Ajax中定义数据的方式,我刚刚使用了serialiarray()和教程( https://madebydenis.com/ajax-load-posts-on-wordpress/)I 已经看到他们正在向下面的数据添加更多的内容;

    data: {
        'cat': cat,
        'ppp': ppp,
        'offset': offset,
        'action': 'mytheme_more_post_ajax'
    }
    

    有没有方法可以添加serializearray()来获取JSON数据?或者我应该换一种方式?

    这是我完整的PHP和JS代码,所以您可以看到到目前为止我的过滤器是如何工作的;

    函数.php

    function custom_js_css(){
        wp_enqueue_script('all_js', get_template_directory_uri() . '/js/all.min.js', 'jquery', '1.0', true);
        wp_localize_script( 'all_js', 'ajax_url', admin_url('admin-ajax.php') );
    }
    add_action('wp_enqueue_scripts', 'custom_js_css');
    
    add_action('wp_ajax_forsalefilter', 'for_sale_filter');
    add_action('wp_ajax_nopriv_forsalefilter', 'for_sale_filter');
    
    function for_sale_filter(){
        $posts = array(
            'posts_per_page'    =>  -1,
            'post_type'         =>  'property',
            'orderby'           =>  'date',
            'meta_key'          =>  'property_status',
            'meta_value'        =>  'For Sale',
        );
    
        $posts['meta_query'] = array( 'relation' => 'AND' );
    
        // price filtering
        if($_GET['min_price'] && !empty($_GET['min_price'])){
            $min_price = $_GET['min_price'];
        }else{
            $min_price = 0;
        }
    
        if($_GET['max_price'] && !empty($_GET['max_price'])){
            $max_price = $_GET['max_price'];
        }else{
            $max_price = 10000000;
        }
    
        $posts['meta_query'][] = array(
            'key'       => 'property_price',
            'type'      => 'NUMERIC',
            'value'     => array($min_price, $max_price),
            'compare'   => 'BETWEEN'
        );
    
        // bed filtering
    
        if($_GET['min_beds'] && !empty($_GET['min_beds'])){
            $min_beds = $_GET['min_beds'];
        }else{
            $min_beds = '1'; 
        }
    
        if($_GET['max_beds'] && !empty($_GET['max_beds'])){
            $max_beds = $_GET['max_beds'];
        }else{
            $max_beds = '9+'; 
        }
    
        $posts['meta_query'][] = array(
            'key'       => 'bedrooms',
            'value'     => array($min_beds, $max_beds),
            'compare'   => 'BETWEEN'
        );
    
        //location filtering
    
        if(isset( $_GET['location'] ) && $_GET['location']){
            $location = $_GET['location'];
            $location_val = stripslashes($location);
    
            $posts['meta_query'][] = array(
                'relation'  => 'OR',
                array(
                    'key'       => 'street',
                    'value'     => $location_val,
                    'compare'   => 'LIKE'
                ),
    
                array(
                    'key'       => 'town',
                    'value'     => $location_val,
                    'compare'   => 'LIKE'
                ),
    
                array(
                    'key'       => 'county',
                    'value'     => $location_val,
                    'compare'   => 'LIKE'
                ),
    
                array(
                    'key'       => 'postcode',
                    'value'     => $location_val,
                    'compare'   => 'LIKE'
                )
            );                          
        }
    
        // property type filtering
        if(isset( $_GET['type'] ) && $_GET['type']){
            $posts['meta_query'][] = array(
                'key'       => 'type_of_property',
                'value'     => $_GET['type'],
                'compare'   => 'IN'
            );
        }
    
        // secondary flash filtering
        if(isset( $_GET['flash_type'] ) && $_GET['flash_type']){
            $posts['meta_query'][] = array(
                'key'       => 'optional_category',
                'value'     => $_GET['flash_type'],
                'compare'   => 'IN'
            );
        }
    
        $query = new WP_Query( $posts );
    
        if( $query->have_posts() ){
            $result = array();
    
            while( $query->have_posts() ){
                $query->the_post();
    
                $main_field = get_field('images');
                $first_row = $main_field[0];
                $img = $first_row['image'];
                $img_med = $img['sizes']['medium'];
    
                $result[] = array(
                    "permalink" =>  get_permalink(),
                    "image"     =>  $img_med,
                    "property_type" =>  get_field('type_of_property'),
                    "bedrooms"      => get_field('bedrooms'),
                    "street"        => get_field('street'),
                    "town"          =>  get_field('town'),
                    "price"         =>  get_field('property_price'),
                    "second_flash"  =>  get_field('optional_category'),
                    "status"        =>  get_field('property_status')
                );
            }
            echo json_encode($result);
        }
        wp_die();
    }
    

    JS公司

    jQuery(function($){
        $('#filters').submit(function(e){
            e.preventDefault();
    
            var filter = $('#filters');
            var root_dir = document.location.origin;
    
            $.ajax({
                url: ajax_url,
                data: filter.serializeArray(), // form data
                dataType: 'json',
                beforeSend:function(xhr){
                    $('#properties').html("\
                        <div id='property_preloader'>\
                          <div id='gif'>\
                                <img src='http://domain.co.uk/wp-content/themes/dist/imgs/preloader.gif' alt='Preloader Icon'>\
                            </div>\
                        </div>"
                     );
                },
                success:function(response){
                    $('#response').empty();
                    $('#properties').html(""+
                        "<div class='container'>"+
                            "<div class='row'><div class='col-12'><div id='crumb'></div><div id='flash_crumbs'></div></div></div>"+
                            "<div class='row' id='response'></div>"+ 
                        "</div>");
    
                    for(var i = 0; i < response.length; i++){
                        var status = response[i].status;
                        var flash_url;
    
                        if(response[i].status == "For Sale"){
                            flash_url = root_dir + '/wp-content/themes/dist/imgs/forsale.svg';
                        }else if(response[i].status == "Sold"){
                            flash_url = root_dir + '/wp-content/themes/dist/imgs/sold.svg';
                        }else{
                            flash_url = root_dir + '/wp-content/themes/dist/imgs/sstc.svg';
                        }
    
                        var html =""+
                            "<div class='col-sm-6 col-md-4 col-lg-3 post'>" +
                                "<div class='shadowwrapper2'>" +
                                    "<a href='" + response[i].permalink + "'>" +
                                        "<div class='propertywrapper'>" +
                                            "<img class='img-fluid gal_imgs' src='" + response[i].image + "' alt='alt'/>" +
                                            "<span class='second_flash'>" + response[i].second_flash + "</span>" +
                                        "</div>" +
                                        "<div class='cornerflash'><img src='" + flash_url + "' alt='corner flash'></div>" +
                                        "<div class='propertyinfo'>" +
                                            "<div class='row m-0'>" +
                                                "<div class='col-6 p-0 mt-2'>" + response[i].property_type + "</div>" +
                                                "<div class='col-6 p-0 mt-2'>" + response[i].bedrooms + " bedrooms</div>" +
                                            "</div>" +
                                        "</div>" +
                                        "<div class='streetpricewrapper'>" +
                                            "<p class='streetname'>" + response[i].street + ", " + response[i].town + "</p>" +
                                            "<p class='price'>£" + response[i].price + "</p>" + 
                                        "</div>" +                    
                                    "</a>" +
                                "</div>" +
                            "</div>";
    
                        $('#response').append(html);
                    }
                    crumb(); 
                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    $('#properties').html(""+
                        "<div class='container'>"+
                            "<div class='row'><div class='col-12'><div id='crumb'></div><div id='flash_crumbs'></div></div></div>"+
                            "<div class='row' id='response'></div>"+ 
                        "</div>");
    
                    var html = "<div class='col-12'><p>Sorry we found no results for your search. Please try widen your search</p></div>";
                    $('#response').html(html);
                    crumb();
                } 
            });
        });
    });
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   random_user_name    6 年前

    serializeArray 创建对象数组(即 收集 )。你可以简单地 push 数组中的新元素,就像这样;

        // using $ notation in variable to indicate a jQuery object
        var $filter = $('#filters');
        // serialize here, so you can add to it before passing in AJAX call...
        var filter = $filter.serializeArray();
        filter.push({ offset: 2 }); // or whatever offset you need to push on....
        // you could add more here if needed....
        filter.push( { other_value: 'foo' } );
    
        var root_dir = document.location.origin;
    
        $.ajax({
            url: ajax_url,
            // send the filter variable here, instead of serializing here...
            data: filter,
            // .... remainder of your code ....