首页 > 解决方案 > AJAX 不返回对象

问题描述

我最初为我的帖子创建了一些过滤器,其中我的 functions.php 文件将返回 html,但是有很多 html,所以我决定我应该使用 JSON 将数据传递给 jQuery,然后从我的 js 文件中输出 html。但是我现在遇到的问题是,当我将响应输出到控制台时,我只会得到文本。

例如,我正在尝试获取每个帖子的永久链接,并且我在一个大段中收到以下内容;

[{"permalink":"http:\/\/websitename.co.uk\/property\/rumballs-court-bishops-stortford-hertfordshire-cm23-copy-2\/"},

{"permalink":"http:\/\/websitename.co.uk\/property\/high-wych-road-sawbridgeworth-hertfordshire-cm21-copy\/"},

{"permalink":"http:\/\/websitename.co.uk\/property\/grovebury-house-galloway-road-bishops-stortford-hertfordshire-cm23-copy\/"},

{"permalink":"http:\/\/websitename.co.uk\/property\/rumballs-court-bishops-stortford-hertfordshire-cm23\/"}]

我不应该收到一个对象而不仅仅是一个段落吗?

这是我的代码;

函数.php

function custom_js_css(){
    wp_enqueue_script('all_js', get_template_directory_uri() . '/js/all.min.js', 'jquery', null, true);
    wp_enqueue_style('all_css', get_template_directory_uri() . '/css/main.min.css');

    wp_localize_script( 'all_js', 'ajax_url', admin_url('admin-ajax.php') );
}
add_action('wp_enqueue_scripts', 'custom_js_css');

add_action('wp_ajax_soldfilter', 'sold_filter');
add_action('wp_ajax_nopriv_soldfilter', 'sold_filter');

function sold_filter(){
    $posts = array(
        'posts_per_page'    =>  -1,
        'post_type'         =>  'property',
        'orderby'           =>  'date',
        'meta_key'          => 'property_status',
        'meta_value'        => 'Sold'
    );

    $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 );?>



    <?php if( $query->have_posts() ): ?>
        <?php 
        $result = array();

        while( $query->have_posts() ): $query->the_post() ?>
            <?php
                $result[] = array(
                    "permalink" =>  get_permalink(),
                );
            ?>
        <?php endwhile; ?>
    <?php

    echo json_encode($result);
    // wp_reset_postdata(); 
    endif; 
    wp_die();
} 

在 sold.php 页面内形成表格

<form action="" method="GET" id="filters">
    <div id="top_bar">
        <input id="location_search" type="text" placeholder="Enter a search location" name="location">

        <label id="type_button">Property Type <span class="arrow">&#9660;<span></label>

        <div id="beds">
            <select name="min_beds">
                <option value="" disabled selected>Min Beds</option>
                <option value="1">1 Bed</option>
                <option value="2">2 Bed</option>
                <option value="3">3 Bed</option>
                <option value="4">4 Bed</option>
                <option value="5">5 Bed</option>
                <option value="6">6 Bed</option>
                <option value="7">7 Bed</option>
                <option value="8">8 Bed</option>
                <option value="9+">9+ Bed</option>
            </select>
            <p>to</p>
            <select name="max_beds">
                <option value="" disabled selected>Max Beds</option>
                <option value="1">1 Bed</option>
                <option value="2">2 Bed</option>
                <option value="3">3 Bed</option>
                <option value="4">4 Bed</option>
                <option value="5">5 Bed</option>
                <option value="6">6 Bed</option>
                <option value="7">7 Bed</option>
                <option value="8">8 Bed</option>
                <option value="9+">9+ Bed</option>
            </select>
        </div>

        <div id="price">
            <select name="min_price"">
                <?php for($x = 0; $x <= 2000000; $x += 100000): ?>
                    <?php if($x == 0): ?>
                        <option value="" disabled selected>Min Price</option>
                    <?php else: ?>  
                        <option value="<?php echo $x; ?>"><?php echo $x; ?></option>
                    <?php endif; ?>     
                <?php endfor; ?>
            </select>
            <p>to</p>
            <select name="max_price">
                <?php for($x = 0; $x <= 2000000; $x += 100000): ?>
                    <?php if($x == 0): ?>
                        <option value="" disabled selected>Max Price</option>
                    <?php else: ?>      
                        <option value="<?php echo $x; ?>"><?php echo $x; ?></option>    
                    <?php endif; ?>
                <?php endfor; ?>
            </select>
        </div>

        <label id="filters_button">Filters <span class="arrow">&#9660;</span></label>
    </div>

    <div id="dropdowns">
        <div id="property_types">
            <div class="column">
                <div>
                    <input type="checkbox" name="type[]" value="Detached" >
                    <img src="<?php bloginfo('template_directory'); ?>/imgs/house_icon.png" alt="house type icon">
                    <p>Detached</p>
                </div>
            </div>

            <div class="column">
                <div>
                    <input type="checkbox" name="type[]" value="Semi-Detached">
                    <img src="<?php bloginfo('template_directory'); ?>/imgs/house_icon.png" alt="house type icon">
                    <p>Semi-Detached</p>
                </div>
            </div>

            <div class="column">
                <div>
                    <input type="checkbox" name="type[]" value="Terraced">
                    <img src="<?php bloginfo('template_directory'); ?>/imgs/house_icon.png" alt="house type icon">
                    <p>Terraced</p>
                </div>
            </div>

            <div class="column">
                <div>
                    <input type="checkbox" name="type[]" value="End of Terrace">
                    <img src="<?php bloginfo('template_directory'); ?>/imgs/house_icon.png" alt="house type icon">
                    <p>End of Terrace</p>
                </div>
            </div>

            <div class="column">
                <div>
                    <input type="checkbox" name="type[]" value="Apartment">
                    <img src="<?php bloginfo('template_directory'); ?>/imgs/house_icon.png" alt="house type icon">
                    <p>Apartment</p>
                </div>
            </div>

            <div class="column">
                <div>
                    <input type="checkbox" name="type[]" value="Bungalow">
                    <img src="<?php bloginfo('template_directory'); ?>/imgs/house_icon.png" alt="house type icon">
                    <p>Bungalow</p>
                </div>
            </div>

            <div class="column">
                <div>
                    <input type="checkbox" name="type[]" value="Commercial">
                    <img src="<?php bloginfo('template_directory'); ?>/imgs/house_icon.png" alt="house type icon">
                    <p>Commercial</p>
                </div>
            </div>
        </div>

        <div id="filters_dropdown">
            <div class="column">
                <label for="first_time">Ideal First Time Buy</label>
                <input id="first_time" type="checkbox" name="flash_type[]" value="Ideal First Time Buy">
            </div>

            <div class="column">
                <label for="investment">Ideal Investment</label>
                <input id="investment" type="checkbox" name="flash_type[]" value="Ideal Investment">
            </div>

            <div class="column">
                <label for="under_offer">Under Offer</label>
                <input id="under_offer" type="checkbox" name="flash_type[]" value="Under Offer">
            </div>
        </div>
    </div>

    <button id="button" type="submit" style="display: none;">Apply filters</button>
    <input type="hidden" name="action" value="soldfilter">
</form>

js

jQuery(function($){
    $('#filters').submit(function(e){
        e.preventDefault();

        var filter = $('#filters');


        $.ajax({
            url: ajax_url,
            data: filter.serializeArray(), // form data
            // type:filter.attr('method'), // POST
            success:function(response){
                // for(var i = 0; i < response.length; i++){
                //     console.log(response[i]);
                // }
                    console.log(response);


                // $('#response').html(data);
                // post_count();
            }
        });
        // return false;

        // console.log(data);
    });
});

如果我使用您可以在 js 文件中看到的 for 循环输出响应,我会得到相同的段落,但每行有一个字符

标签: phpjquerywordpress

解决方案


您正在获得应该在使用前解析的 ajax 编码字符串。否则它只是一个刺痛,.so

jQuery(function($){
$('#filters').submit(function(e){
    e.preventDefault();

    var filter = $('#filters');


    $.ajax({
        url: ajax_url,
        data: filter.serializeArray(), // form data
         type: POST
        success:function(response){
         var  data = JSON.parse(responce);
             for(var i = 0; i < data.length; i++){
                console.log(data[i]);
             }

    });

});
});

应该管用。


推荐阅读