【问题标题】:Ajax call within WordPress returning entire HTML page in responseWordPress 中的 Ajax 调用返回整个 HTML 页面作为响应
【发布时间】:2021-07-26 09:28:59
【问题描述】:

最令人沮丧的是,这段代码可以正常工作,然后突然开始返回整个 HTML 页面,而不仅仅是下面模板中的 HTML 代码。

我正在调用一个 ajax 函数并向其传递一个如下所示的对象(console.log(data) 的结果):

这是我的 ajax 函数:

function mapResults (data) {

        //console.log(data);

        $.ajax({
            type: 'post',
            url: wp_ajax.wp_url,
            data: {action: 'marker_in_viewport', resultsArray: data},
            success: function(result) {
                $('#map-results').html(result);
            },
            error: function(result) {
                console.warn(result);
            }
        });

    }

这是处理请求的 PHP 代码:

<?php
add_action( 'wp_ajax_nopriv_marker_in_viewport', 'marker_in_viewport');
add_action( 'wp_ajax_marker_in_viewport', 'marker_in_viewport');

function marker_in_viewport() {

    $locationResults = $_POST['resultsArray'];

      $posts = get_posts(array(
        'post_type' => 'accommodation',
        'post__in' => $locationResults,
        
    ));  

    ?>

    <?php

        //require result template
        //require_once ('map-results.php');

        if( $posts ) { ?>     
            
            <?php foreach( $posts as $post ) {
        
                            $id = $post->ID;
                            $title = get_the_title($id);
                            $location = get_field('location', $id);
                            $permalink = get_permalink( $id );
                            $rooms_available_from = get_field('rooms_available_from', $id);
                            $gallery = get_field('gallery', $id);
        
                            ?>
        
                            <div class="col-md-4 accom-results-cont pb-3">
        
                            <?php if ($gallery) : ?>
        
                                <a href="<?= $permalink; ?>" title="Learn more about <?= $title; ?>">
        
                                    <div class="accom-results-img-cont">
                                
                                        <img class="img-fluid" src="<?= $gallery['url']; ?>" alt="An image of <?= $title; ?>" >
        
                                    </div>
        
                                
        
                            <?php endif; ?>
        
                                
        
                                    <div class="accom-results-data-cont pr-3 pt-3">
        
                                        <?php if ( $title ) : ?>
        
                                            <p class="results-title"><b><?= $title ?></b></p>
        
                                        <?php endif; ?>
        
                                       
        
                                        
        
                                    </div>
                            
                                </a>
                            
                            </div>
        
                        <?php } ?>
        
        <?php } ?>    

<?php wp_die(); ?>

<?php } ?>

在我的页面模板中,我有以下 div,我希望在其中填充结果:

<div id="map-results"class="row py-5"></div>

任何想法我做错了什么?

【问题讨论】:

    标签: javascript jquery ajax wordpress advanced-custom-fields


    【解决方案1】:

    我修改了你的代码。试试下面的代码。

    function mapResults (data) {
    
        $.ajax({
            type: 'post',
            dataType : "json",
            url: wp_ajax.wp_url,
            data: {action: 'marker_in_viewport', resultsArray: data},
            success: function(result) {
                $('#map-results').html(result.data.html);
            },error: function(result) {
                console.warn(result);
            }
        });
    
    }
    

    您可以使用ob_start()ob_get_clean()

    add_action( 'wp_ajax_nopriv_marker_in_viewport', 'marker_in_viewport');
    add_action( 'wp_ajax_marker_in_viewport', 'marker_in_viewport');
    
    function marker_in_viewport() {
    
        $locationResults = $_POST['resultsArray'];
    
        $posts = get_posts(array(
            'post_type' => 'accommodation',
            'post__in'  => $locationResults    
        ));  
    
        ob_start();
    
        if( $posts ) {  foreach( $posts as $post ) {
    
            $id        = $post->ID;
            $title     = get_the_title($id);
            $location  = get_field('location', $id);
            $permalink = get_permalink( $id );
            $gallery   = get_field('gallery', $id);
            $rooms_available_from = get_field('rooms_available_from', $id);
            ?>
            <div class="col-md-4 accom-results-cont pb-3">
                <a href="<?php echo $permalink; ?>" title="Learn more about <?php echo $title; ?>">
                    <?php if ( $gallery ) : ?>
                        <div class="accom-results-img-cont">
                            <img class="img-fluid" src="<?php echo $gallery['url']; ?>" alt="An image of <?php echo $title; ?>" >
                        </div>
                    <?php endif; ?>
                    <div class="accom-results-data-cont pr-3 pt-3">
                        <?php if ( $title ) : ?>
                            <p class="results-title"><b><?php echo $title; ?></b></p>
                        <?php endif; ?>
                    </div>
                </a>
            </div>
    
        <?php } } 
    
        $html = ob_get_clean();
    
        wp_send_json_success(array(
            'html' => $html
        ));
        
    }
    

    有用的链接

    【讨论】:

    • 我同意 - 使用 ob_start()ob_get_clean() 可能会有很大帮助。
    • 您好感谢您查看代码,它现在在 ajax 调用的错误函数中返回警告。 Console.warn(result) undefined.
    • 我怀疑从我的 ajax 函数发送的数据没有到达正确的 php 函数,有没有办法测试这个?
    【解决方案2】:

    经过大约一周的尝试,终于成功了!

    这是我在 js/script.js 中的 AJAX 函数

     $.ajax({
                type: 'post',
                //dataType: 'json',
                url: map_ajax_obj.ajaxurl,
                data: {action: 'marker_in_viewport', resultsArray: data, nonce: map_ajax_obj.nonce},
                success: function(result) {
                    //console.log(result);
                    $('#map-results').html(result);
                },
                error: function(result) {
                    console.warn(result);
                }
            });
    

    在我的functions.php文件中,我已经像这样将我的wp-admin.php排入队列并本地化了

        function load_req_scripts()
        {
            wp_register_script( 'custom-js-script', get_template_directory_uri() . '/js/script.js', array( 'jquery'), '', true);
            wp_enqueue_script( 'custom-js-script' );
        
            wp_localize_script(
                'custom-js-script', //I think this is a dependancy on the above script though not entirely sure
                'map_ajax_obj',
                array (
                   
                    'ajaxurl' => admin_url('admin-ajax.php'), 
                    'nonce'  => wp_create_nonce('ajax_nonce')
                )
            );
        }
        add_action( 'wp_enqueue_scripts', 'load_req_scripts' );
    
    require_once('ajax/accommodation-ajax.php'); //where to handle and return the data to the ajax call
    

    这是我的 accommodation-ajax.php 文件中的函数

    <?php
    
    function marker_in_viewport() {
    
        $locationResults = $_POST['resultsArray'];
    
        if (!empty($locationResults)) {
    
        $posts = get_posts(array(
            'post_type' => 'accommodation',
            'post__in'  => $locationResults    
        ));
    
        if( $posts ) {  
            
            foreach( $posts as $post ) {
    
            $id        = $post->ID;
            $title     = get_the_title($id);
            $location  = get_field('location', $id);
            $permalink = get_permalink( $id );
            $gallery   = get_field('gallery', $id);
            $rooms_available_from = get_field('rooms_available_from', $id);
            ?>
            <div class="col-md-4 accom-results-cont pb-3">
                <a href="<?php echo $permalink; ?>" title="Learn more about <?php echo $title; ?>">
                    <?php if ( $gallery ) : ?>
                        <div class="accom-results-img-cont">
                            <img class="img-fluid" src="<?php echo $gallery['url']; ?>" alt="An image of <?php echo $title; ?>" >
                        </div>
                    <?php endif; ?>
                    <div class="accom-results-data-cont pr-3 pt-3">
                        <?php if ( $title ) : ?>
                            <p class="results-title"><b><?php echo $title; ?></b></p>
                        <?php endif; ?>
                    </div>
                </a>
            </div>
        <?php } //end for each 
        
        } //end if posts
    
        } //end if not empty
    
        else {
    
            echo "No results found please search again!";
    
        }
    
        wp_die();
    }
    
    add_action( 'wp_ajax_nopriv_marker_in_viewport', 'marker_in_viewport');
    add_action( 'wp_ajax_marker_in_viewport', 'marker_in_viewport');
    

    至于为什么这与我上面发布的内容相比现在有效,我不知道!会不会是 NONCE?虽然我没有使用它在 PHP 函数中进行身份验证。无论如何,希望下次我用 wordpress ajax 调用将头撞到墙上时,这对某人或我未来的自己有所帮助。

    更新 所以这对我来说再次停止工作,然后我意识到它在以管理员身份登录时工作,而不是为注销和所有其他用户工作。因为这是一个会员网站,所以我想阻止任何不是管理区域管理员的人。没有意识到这个函数也阻止了对 admin-ajax.php 文件的访问。这是重定向到主页,因此 AJAX 调用返回整个页面 HTML。

    所以我需要更新我的功能以包括:

    && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX )
    

    到以下:

    //block users from admin if not admin
    function blockusers_wps_init() {
            if ( is_admin() && ! current_user_can( 'administrator' ) && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
                    wp_redirect( home_url() );
                    exit;
            }
    }
    
    add_action( 'init', 'blockusers_wps_init' );
    

    【讨论】:

      【解决方案3】:

      不要使用 wp_die() 它返回 html,只使用 die()

      【讨论】:

      • die(); 替换wp_die(); 似乎不起作用。
      猜你喜欢
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多