繁体   English   中英

Ajax 在 WordPress 中调用返回整个 HTML 页面作为响应

[英]Ajax call within WordPress returning entire HTML page in response

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

我打电话给 ajax function 并传递给它一个 object 看起来像这样(console.log(数据)的结果):

console.log(data) 截图

这是我的 ajax function:

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>

任何想法我做错了什么?

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

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
    ));
    
}

有用的链接

经过大约一周的尝试后终于得到了这个工作!

这是我在 js/script.js 中的 AJAX Function

 $.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);
            }
        });

在我的函数中

    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

这是我的住宿-ajax.php 文件中的 function

<?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 电话撞墙时,这对某人或我未来的自己有所帮助。

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

所以我需要更新我的 function 以包括:

&& ( ! 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' );

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM